I have a file that I need to read, print out the integers, catch exception and continue with the next integer to display, and so on until there are no more integers.
The file contains: 12 5 sd 67 4 cy
I want it to display:
12
5
Input error
67
4
Input error
However, it only gives me 12, 5, followed by input error, and it stops. I've tried putting everything into a while loop and it loops endlessly with the input exception.
public static void readNumbers()
{
File inputFile = new File ("C:/users/AC/Desktop/input.txt");
try
{
Scanner reader = new Scanner(inputFile);
while(reader.hasNext())
{
int num = reader.nextInt();
System.out.println("Number read: " +num);
}
}
catch (InputMismatchException e)
{
System.out.println("Input error ");
}
catch (FileNotFoundException e2)
{
System.out.println("File not found!");
}
}
}
What am I missing so that the loop continues reading the next int and so on?
See Question&Answers more detail:os