-7

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

public class Main { public static void main(String args[]){

    int total = 0;

    File file = new File("expenditure.txt");
    Scanner fileScanner = new Scanner(file);

    while (fileScanner.hasNextLine()) {
        total += fileScanner.nextInt();
        }
        fileScanner.close();

    System.out.println("The total expenditure is " + total);
}

}

  • [Lesson: Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions) – MadProgrammer Jul 11 '19 at 05:47
  • 4
    Possible duplicates [error: unreported exception FileNotFoundException; must be caught or declared to be thrown](https://stackoverflow.com/questions/19788989/error-unreported-exception-filenotfoundexception-must-be-caught-or-declared-to) and [unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown](https://stackoverflow.com/questions/5748656/unreported-exception-java-io-filenotfoundexception-must-be-caught-or-declared-t/5748802) – MadProgrammer Jul 11 '19 at 05:48
  • The Java Tutorials: [The `try-with-resources` Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – Elliott Frisch Jul 11 '19 at 05:49

1 Answers1

-1

Surround your reading of file with a try-catch, sample code below:

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

public class Main {
    public static void main(String args[]){

        try {
            int total = 0;

            File file = new File("expenditure.txt");
            Scanner fileScanner = new Scanner(file);

            while (fileScanner.hasNextLine()) {
                total += fileScanner.nextInt();
            }
            fileScanner.close();

            System.out.println("The total expenditure is " + total);
        } catch (FileNotFoundException ex){
            System.out.println("File not found");
        }
    }
}

Mark Melgo
  • 1,477
  • 1
  • 13
  • 30