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

Answer:

See below.

Whenever there is a sum, be sure that it is initialized to zero. Whenever there is a count, be sure that it is initialized (usually to zero or one) and check for off-by-one problems.


Complete Program

import java.util.Scanner;

class AddUpFile
{
  public static void main ( String[] args )  
  {
    Scanner scan = new Scanner( System.in );
    int value;
    int sum = 0 ;       // initialize sum

    int count = 1 ;     // initialize count
    while ( count <= 100 )
    {
      System.out.print("Enter a number: ") ;
      value  = scan.nextInt() ;    // get next integer
      sum    = sum + value;        // add to the sum
      count  = count + 1 ;         // increment count
    }

    System.out.println( "Grand Total: " + sum );
  }
}

If you run this program as is you must enter 100 integers. This could be tedious. For testing purposes change "100" to a smaller number.


QUESTION 11:

Say that you do have a file of 100 integers and run the program by doing this:

C:\java AddUpFile < largeData.txt

What will the user see on the monitor?