Scanner, nextInt and InputMismatchException
I'm trying to read a text file and then print out the integers in a loop using the nextInt() function in Java. The text file I have is of the form:
a 2000 2
b 3000 1
c 4000 5
d 5000 6
Here is my code:
public static void main(String[] args) throws FileNotFoundException {
String fileSpecified = args[0] + ".txt";
FileReader fr = new FileReader(fileSpecified);
BufferedReader br = new BufferedReader (fr);
Scanner in = new Scanner (br);
while (in.hasNextLine()) {
System.out.println ("next int = " + in.nextInt());
}
}
The error I always get is:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
开发者_开发技巧 at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
I get this error everytime I use nextInt() in any program.
I think it will be finding the characters e.g. "a","b","c" which is a String and failing to take it as an int. You can figure this out by debugging with:
System.out.println ("next value= " + in.next());
//System.out.println ("next int = " + in.nextInt());
You could alternatively use the API guard to prevent this e.g.
if(in.hasNextInt()) {
System.out.println ("next int = " + in.nextInt());
}
You probably want something like this instead:
while (in.hasNext()) {
System.out.println("letter = " + in.next());
System.out.println("integer1 = " + in.nextInt());
System.out.println("integer2 = " + in.nextInt());
}
hasNextLine doesn't mean that the next value is an int. The input file that you posted contains e.g. "a", and that isn't an int.
精彩评论