No.
No data is "consumed" when a hasNext()
method is used.
This means that the next token in the file can be tested by using several
hasNext()
methods to determine what it is.
The following version of the program reads a file and prints the square of any text integers in it. Words in the file are skipped over.
import java.util.Scanner; import java.io.*; class ManySquaresSkipWords { public static void main (String[] args) throws IOException { File file = new File("myData.txt"); // create a File object Scanner scan = new Scanner( file ); // connect a Scanner to the file int num, square; while ( scan.hasNext() ) // is there more data to process? { if ( scan.hasNextInt() ) // if it is an integer, get it { num = scan.nextInt(); square = num * num ; System.out.println("The square of " + num + " is " + square); } else scan.next(); // read and discard non-integers } } }
Is a program that always reads its data from the same file likely to be useful?