My Try Catch block isn't catching the right value from a file.
I have my code using a NumberFormatException for reading in a file of integers. When it reads in from the given file, it is supposed to catch all the non-integers and display a message saying which values are not integers. When I run my program, it says that 200 and 150 (the integers right before the words) are the non-integers... any idea why? Here is the file to read from with my code following it.
File lab10data.txt
Code:
100
200
bogus
300
150
weasel
400
600
250
3.5
800
50
500
450
600
550
lab10.java
Code:
import java.util.*;
import java.io.*;
public class lab10
{
public static void main(String [] args)
{
Scanner inScan, fScan = null;
String fName;
String nextItem;
int nextInt = 0;
int i = 0;
int [] A = new int[5];
File file;
try {
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");
fName = inScan.nextLine();
file = new File(fName);
while (!file.exists()) {
System.out.println("Please enter the file to read from: ");
fName = inScan.nextLine();
file = new File(fName);
}
fScan = new Scanner(file);
while (fScan.hasNextLine())
{
try {
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
catch (NumberFormatException nonInt) {
System.out.println(nextInt + " is not an integer -- ignored.");
}
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
catch (FileNotFoundException bad) {
fName = null;
}
}
}