Showing posts with label nextInt(). Show all posts
Showing posts with label nextInt(). Show all posts

Sunday, March 18, 2012

Scanner class - Part 1

DOWNLOAD THE CODE: Scanner.zip

The Scanner class has methods for reading a number of different types of data such as String, int, Double & Boolean.

By default, the Scanner class uses whitespace to delineate tokens (lines, words, phrases, values, etc).

We can use the Scanner class to read input from keyboard input or from txt files.

Use Scanner to read keyboard input
The example below uses the Scanner class to read keyboard input. Scanner contains several methods for reading different types of data. In this example, the next() & nextInt() methods are used to read the input String and the input int, respectively.


The output:




Using Scanner to read from a text file
The following shoppinglist.txt file contains a number of shopping items. Each item is followed by a number representing the quantity required.


Declare an instance of File and then declare an instance of the Scanner class. Pass the file instance to the scanner instance.

The Scanner class contains a number of Boolean functions to determine whether there is another token of a specified type. The example below uses a while loop in conjunction with the Scanner's hasNext() method of Scanner to determine if another token of any type exists.  In effect, the loop has been primed to 'continue looping while there are more tokens to read'. When there are no more toekn to read, the loop will stop.




The output: 



The final token in this example is the character 1.

By default, the Scanner's next() method is using the whitespace separating the characters in the file, to delineate is string. As such, any string separated by whitespace, is being read in each pass of the loop. The statement input.next() reads the next token in the file.

Let's change the code a little to get these values onto the same line.

The while loop body now looks like this:


The first call to next() reads in the name of the shopping item and is printed to screen via the print() method. The second call to next() is used to read in the quantity is appended to the next line via the println() method. 

The output now looks like this:


Read on to learn about using a nominated deliminator character with the Scanner class.



"Scanner (Java Platform SE 7 )" ( http://bit.ly/ABSuGl )


Simple tutorial using the Scanner class: "Java For Complete Beginners - user input" ( http://bit.ly/Lkr7uN )

"Scanning (The Java™ Tutorials > Essential Classes > Basic I/O)" ( http://bit.ly/LkD03X )

"File (Java Platform SE 7 )" ( http://bit.ly/Jxdc9T )

"The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/LkGjIm )