I am attempting to read a bunch of numbers from a file and add them up. But I have added a few Strings in the File also. I am now trying to read the numbers add them together and using the try/catch block I am trying to display an error when the file reads a string instead of a integer. However as soon as the code reads a string from the file it gives me the error, the code does not continue to add the numbers together. It simply prints the error and prints 0. How do I modify it so that it continues to read the numbers and add them together as well as display an Error message after it reads a string.
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class AddNumbers {
public static void main (String[]args) {
try{
File myFile = new File("numbers.txt");
Scanner scan = new Scanner(myFile);
int x;
int y = 0;
try{
//Read file while it has a line
while(scan.hasNextLine()){
//scan a integer value
x = scan.nextInt();
//Add the scanned value to y
y = y+x;
}
}catch(InputMismatchException e){
//If a string is found then print this error
System.err.println("Strings found! Error!");
}
System.out.println(y);
scan.close();
}catch(FileNotFoundException e){
System.err.println("No such file exists!");
System.out.println();
}
}
}
File Contents
Albert
10000
20000
30000
Ben
50000
12000
Charlie