I need to use InputMismatchException and FileNotFoundExeption with a try catch. I got the file not found exception to work but my input mismatch exception wont work and I don't know why.
i have two test files for this. the code essentially is supposed to add up all the numbers in a file and report the answer. my test file 1 is simple the numbers are 1.0 2.0 3.0 4.0 and 5.0, it works and adds up to 15 and gives me back 15 like its supposed top. If i put in a bad file name my first exception works and it says file does not exist.
my second test file says 1.0 2.0 3f 4.0 and 5.0. when i use my second file its supposed to say only numbers are accepted, instead it just gives me back a 3, i guess it just stops at 3 once it sees the f and quits the program. i want it to say only numbers accepted.
can someone help here is my code:
import java.util.*; import java.io.*; public class Program2 { public static void main(String []args) { try { Scanner i = new Scanner(System.in); System.out.println("Enter The File Name: "); String file = i.nextLine(); File input = new File(file); Scanner out = new Scanner(input); double total = 0; while(out.hasNextDouble()) { total += out.nextDouble(); } System.out.println(total); } catch (FileNotFoundException e) { System.out.println("File does not exist."); } catch (InputMismatchException e) { System.out.println("Only Numbers are accepted."); } } }