The Java Scanner example, continued
The tutor continues discussing yesterday’s Java Scanner example.
In yesterday’s post I introduced a short program to test an instance of the Java Scanner.
As of today, I’ve tried the program on both my Windows and my Linux systems. It seems to work well on both.
The point of the program is to test the Java Scanner’s ability to find numbers among other text. For instance, does it know that $45.67 is a number? How about 4.1e-2 (0.041 in scientific notation). Or 6.75d? (The “d” indicates type “double” in some Java contexts.)
In the program, the wordings
scan0.hasNextDouble()
and
scan0.nextDouble()
mean that the scanner is looking for numbers of “double” type; i.e., decimals. (Using other methods, the scanner could be set to look for integers, strings, or other types of values.)
I first compiled the program thus:
javac TryScanner.java
Afterwards, I ran several tests. Here’s one of my command line calls:
java -cp . TryScanner 78.1 here 45 $76.51 4.2e-3 655.2d
The output:
Readable number: 78.1
Not a readable number: here
Readable number: 45.0
Not a readable number: $76.51
Readable number: 0.0042
Not a readable number: 655.2d
See you again:)
So we see that the Java Scanner, in this example anyway, does not appreciate that $76.51 means a number. It does, however, recognize 4.2e-3 as 0.0042, and 45 as 45.0.
The call above was done on Windows; my Linux system mostly agrees, but not in every case (surprise, surprise….:) More on that next time.
I realize that, with Java programming, I’ve opened an accordion file that could wrap around the world.
Source:
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.