Source of SumAllFromFile.java


  1: // SumAllFromFile.java
  2: //  read and sum all the numbers from a file
  3: // revised from Sum3B_FromFile

  5: import java.util.Scanner;
  6: import java.io.File;
  7: import java.io.FileNotFoundException;

  9: /**
 10:  * Read and sum all numbers from 3Nums.txt
 11:  * (which actually has 4 numbers in it).
 12:  * @see Sum3B_FromFile.java
 13:  *
 14:  * @author Mark Young (A00000000)
 15:  */
 16: public class SumAllFromFile {

 18:     public static void main(String[] args) 
 19:             throws FileNotFoundException {
 20:         Scanner fin = new Scanner(new File("3Nums.txt"));
 21:         // replace n1,n2,n3 with num
 22:         int num;
 23:         // create a variable for the sum
 24:         int sum = 0;

 26:         // replaced lines for three separate reads with a loop
 27:         while (fin.hasNextInt()) {
 28:             num = fin.nextInt();
 29:             sum += num;
 30:         }

 32:         // print sum (without echoing input)
 33:         System.out.println("\nThe sum of all those numbers is " + sum + ".\n");
 34:     }

 36: }