Saturday, May 7, 2011

SCANNER

Often we need to read information from the user of the program. We might prompt the user, for example,
to ask them what kind of car they drive. We can ask the question of the user by displaying the question using
System.out.println(). We have shown many examples of displaying information on the screen.
Java provides a class called Scanner that makes it easy to read information from the keyboard into the
program. To create a scanner object for reading from the keyboard, we simply pass the standard input “stream”
to the constructor for a new Scanner. For example, here is a snippet of code to create a new Scanner for
reading from the keyboard, and then to use the Scanner to read a floating-point number:
...
Scanner scanner = new Scanner(System.in);
// Obtain input
System.out.print("Enter balance: ");
double balance = scanner.nextDouble();
...
The Scanner class has many methods, and you should consult the Java API documentation to see what
they are, and what choices you have.
You can also use a Scanner to read from a file. To associate a Scanner with a file of text, just pass
a FileReader object to the Scanner constructor:
sc = new Scanner(new FileReader( myFile.txt ) );
To read lines of text, you can use the nextLine() method of Scanner to transfer a line of text
into a String variable. You can also use the hasNextLine() method to test to see whether there is
something to read. Here’s a snippet of code to loop, reading text for processing into a String called
lineOfData.

String lineOfData;
Scanner sc = new Scanner( myFile.txt );
while( sc.hasNextLine() ) {
lineOfData = sc.nextLine();
...
}//while
When the program reaches the EOF, the hasNextLine() method will return false, and the program will
exit the while loop.

No comments:

Post a Comment