go to previous page   go to home page   go to next page

Answer:

No.


No Data Consumed

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
    }
  }
}

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 above program reads a file and prints the square of any textual integers in it. Words in the file are skipped over.


QUESTION 9:

Would a file containing the following be correctly processed by this program?

Data:
Amy 7000  Bob 5000
Cal -530

Dan 2300
Ed  -310 

Fred 6800  Gail 
7500