Java Reference
In-Depth Information
14.
Let's use the Scanner class to convert a String to an int . Add these Java state-
ments to the end of the previous statement (before the last two braces):
// Let's use the Scanner class to convert a String to an int
inputMsg = "1003";
int x = 0;
Scanner s = new Scanner(inputMsg);
x = s.nextInt();
System.out.println("int from Scanner = " + x);
15. Compile and run this class. Your output window should look like this:
...
int from Scanner = 1003
R EVIEWING THE E XERCISES
Let's review the samples you've created. Try to relate the sample source statements
to the result (for example, the output) each statement creates. If necessary, rerun
the samples, or look at the complete source code for this exercise on the CD-ROM.
Feel free to experiment by yourself.
Java strings are similar to items defined as PIC X in COBOL. Java strings con-
tain characters and have an explicit length attribute.
Java's String class contains many useful methods for manipulating string
items. At the same time, Java's compiler sometimes treats string variables sim-
ilarly to intrinsic data types.
These Java statements:
System.out.println ("compareTo = " +
englishCaps.compareTo (temp));
System.out.println ("equals = " +
englishCaps.equals (temp));
call the compareTo() and then the equals() methods in the object englishCaps.
In both cases, the called method is passed a string parameter ( temp ). The result
of this method is printed using the println() method.
Search WWH ::




Custom Search