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

Answer:

Yes.

Scanner.nextInt() scans through the stream of character data token by token. Each token should be an integer encoded as characters. The newline characters are just more whitespace so far as Scanner.nextInt() is concerned.


Improved Error Handling

Here is a version of the program that deals with non-integers in the data without using Exceptions. The scan.hasNextInt() checks that the next token can be parsed as an int. If so, the true branch of the if scans and parses the token. Otherwise, the false branch scans the next token, but does not try to convert it to an int.

import java.util.*;
import java.io.*;

public class SumFileDataImproved 
{
  public static void main (String[] args) throws IOException 
  { 
    int num,sum = 0;
    Scanner scan = null, scanUser = null;
    String fileName;
    
    try 
    {
      scanUser = new Scanner( System.in );
      System.out.println("Input file name: ");
      fileName = scanUser.nextLine().trim();
      
      File file = new File( fileName ); // create a File object
      scan = new Scanner( file );      // connect a Scanner to the file

      while( scan.hasNext() )   // is there more data to process? 
      {
        if ( scan.hasNextInt() )
        {
          num = scan.nextInt();
          sum += num;  
        }
        else
        {
          System.err.println( "Bad input data: " + scan.next()  + " skipped.");
        }        
      }
      
      System.out.println("Sum = " + sum );
    }
    
    finally 
    {
      if ( scan != null ) scan.close();
    }
  }
}

Here is some poor data, contained in the file poorRobin.txt:

3 6 12 17
14 4 32

23 ten
19

Here is the output of the program

C:\JavaSource> javac SumFileDataImproved.java
C:\JavaSource> java SumFileDataImproved
Input file name:
poorRobin.txt
Bad input data: ten skipped.
Sum = 130

QUESTION 8:

Is the blank line in the data OK?


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