Reading Numbers
In the last example you saw how to read a string. Now I will show you how to read a number. It is necessary to read a number if you want to perform any sort of mathematical operation on what the user has entered.
Probably the easiest way to read a number is to first read a String, and then convert it to a number. Java provides several methods to convert from a string to a numeric type. Which method you use depends on the type of number you want.
- byte: Byte.parseByte(str)
- double: Double.parseDouble(str)
- float: Float.parseFloat(str)
- int: Integer.parseInt(str)
- long: Long.parseLong(str)
- short: Short.parseShort(str)
For this example we will input a number, in miles, and convert that number into kilometers. Listing 4.2 shows this example program.
Listing 4.2: Input Numbers (InputNumbers.java)
import java.io.*;
public class InputNumbers
{
public static void main(String args[])
{
try
{
InputStreamReader inputStreamReader =
new InputStreamReader ( System.in );
BufferedReader in =
new BufferedReader ( inputStreamReader );
System.out.print("Enter a length in miles? ");
String miles = in.readLine();
double dMiles = Double.parseDouble(miles);
double dKilometers = 1.609344 *dMiles;
System.out.println("That is " + dKilometers +
" kilometers.");
}
catch(IOException e)
{
}
}
}As you can see from the above program it is very similar to the previous example where a string was entered into the program.
However, once the string has been read into the variable “miles”, the string is converted into a double. The string is converted into a double, rather than an long, because doubles can have decimal places.
To convert the string into a double, the following line of code is used.
double dMiles = Double.parseDouble(miles);
To convert the number of miles into Kilometers the miles are multiplied by 1.609344. You may want to define a constant, using the final keyword, to hold this number.












