Advertisement
dimipan80

Sum Numbers from a Text File

Aug 20th, 2014
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. /* Write a program to read a text file "Input.txt" holding a sequence
  2.  * of integer numbers, each at a separate line.
  3.  * Print the sum of the numbers at the console.
  4.  * Ensure you close correctly the file in case of exception
  5.  * or in case of normal execution.
  6.  * In case of exception (e.g. the file is missing), print "Error" as a result. */
  7.  
  8. import java.io.File;
  9. import java.util.Scanner;
  10.  
  11. public class _08_SumNumbersFromTextFile {
  12.  
  13.     public static void main(String[] args) {
  14.         // TODO Auto-generated method stub
  15.         File file = new File("Input.txt");
  16.         try (Scanner scan = new Scanner(file);) {
  17.             long sumOfNumbers = 0;
  18.             while (scan.hasNextInt()) {
  19.                 sumOfNumbers += scan.nextInt();
  20.             }
  21.  
  22.             System.out.println("The Sum of Numbers in that File is: "
  23.                     + sumOfNumbers);
  24.         } catch (Exception e) {
  25.             System.out.println("Error!");
  26.         }
  27.     }
  28.  
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement