Dana Vrajitoru
C101 Computer Programming

C101/I210 Homework 8

Due date: Wednesday, March 25, 2020.

Objective: To write methods in Java and work with characters and strings.

Ex. 1. String to Integer

In this homework we will write a method that converts a string to an integer.

Create a Java project in Eclipse called hw8 and in it, a class called String2Int containing the main method.

a. Digit to int

Write a method that takes in a character and converts it to an integer. If the character is in the range from '0' to '9', then it can be converted by subtracting from its code, the code for '0'. If it's outside the range, return 0. The header of the function should be

static int char2int(char c)

b.String to int Write a method that takes in a string and converts it to an integer. For our purposes, we will use only the digits in the string and ignore the other letters. The header of the function should be

static int str2int(String s)

In this function, initialize the number to 0, then use a for loop going from 0 to the length of s. In this loop, first test if the character is a digit. For that you can test the range '0' to '9', or copy the function we wrote in the lab. Then if it is a digit, then multiply the number by 10 and then add the character converted to an integer using a call to the function written at a. If not, then there is nothing to do with that character.

For example, the string "319,214" should convert to the integer 319214.

c. In the main, declare a String variable and then input it from the user using the function next from the Scanner class. Then convert it to an integer using the function str2int and output the result.

Test the program multiple times to make sure it works. Add an example of running the program as comments at the end of the code.

Turn in:

Upload the lab and homework .java files: Fraction8.java, StringCount.java, and String2Int.java, to Canvas in Assignments - Homework 8.