Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program to read a text file "Input.txt" holding a sequence
- * of integer numbers, each at a separate line.
- * Print the sum of the numbers at the console.
- * Ensure you close correctly the file in case of exception
- * or in case of normal execution.
- * In case of exception (e.g. the file is missing), print "Error" as a result. */
- import java.io.File;
- import java.util.Scanner;
- public class _08_SumNumbersFromTextFile {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- File file = new File("Input.txt");
- try (Scanner scan = new Scanner(file);) {
- long sumOfNumbers = 0;
- while (scan.hasNextInt()) {
- sumOfNumbers += scan.nextInt();
- }
- System.out.println("The Sum of Numbers in that File is: "
- + sumOfNumbers);
- } catch (Exception e) {
- System.out.println("Error!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement