Java programming: a Scanner example

Due to popular demand, the tutor shows basic use of a Java Scanner.

I write Java programs for my own needs; I’m not a professional programmer. The following simple Java program illustrates a basic way a scanner can be tested.

The Scanner class is a Java utility that can read separate values from a stream of data. One use of a scanner is to read through a line of data in which a number is expected. If the number is in there, the scanner likely will find it, provided it doesn’t include any non-numeric characters. Also, it seems, the number can’t be “touching” any non-numeric characters; it must be separate from other text.

Here’s the little program I wrote:

import java.util.*;
class TryScanner{
public static void main(String[] args){
for (int i=0;i<args.length;i++){
Scanner scan0=new Scanner(args[i]);
if(scan0.hasNextDouble()){
System.out.println(“Readable number: “+scan0.nextDouble());
}

else{
System.out.println(“Not a readable number: “+scan0.next());
}
}//end of for loop
System.out.println(“\n\nSee you again:)”);
}//end of main() method
}//end of class

I ran this program on Windows; my Linux compiler can be more strict, but I’m optimistic it will work there too.

To the Java programmers who will come looking for a scanner example: hope this helps. For my casual readers who aren’t as familiar with Java, I will be explaining how to get up and running with it in future posts.

Tomorrow, I’ll discuss the program above and some findings from the tests I ran with it:)

Source:

Kurniawan, Budi. Java 5: A Beginner’s Tutorial. 2006: Brainy Software Corp.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply