Java Reference
In-Depth Information
EXAMPLE:
(continued)
The entire line is read as a single long string using the method
nextLine
of the
Scanner
class. The long string is decomposed into tokens using the class
StingTokenizer
. The
tokens are the numbers that were input, but they are in the form of string values, not
values of type
double
. Finally, the tokens are converted to values of type
double
using
the method
Double.parseDouble
.
Note that the
String
variables are initialized to
null
. If you omit the nulls,
the compiler will complain that the variables
string1
and
string2
might not be
initialized before they are used. The compiler is incorrect but it does no good to argue
with it. Including
null
as initial values for the variables
string1
and
string2
will
keep the compiler happy and allow you to run the program.
Display 5.18
Use of the Method
Double.parseDouble
(part 1 of 2)
1
import
java.util.Scanner;
2
import
java.util.StringTokenizer;
3
public class
InputExample
4 {
5
public static void
main(String[] args)
6 {
7 Scanner keyboard =
new
Scanner(System.in);
8 System.out.println("Enter two numbers on a line.");
9 System.out.println("Place a comma between the numbers.");
10 System.out.println("Extra blank space is OK.");
11 String inputLine = keyboard.nextLine();
12 String delimiters = ", ";
//Comma and blank space
13 StringTokenizer numberFactory =
14
new
StringTokenizer(inputLine, delimiters);
15 String string1 =
null
;
16 String string2 =
null
;
17
if
(numberFactory.countTokens() >= 2)
18 {
19 string1 = numberFactory.nextToken();
20 string2 = numberFactory.nextToken();
21 }
22
else
23 {
24 System.out.println("Fatal Error.");
25 System.exit(0);
26 }