Reputation: 33
I'm having a problem with my code that seems like it should be running perfectly.
public void inputFile() {
Scanner reader = null;
try {
reader = new Scanner( new File ("parts.dat"));
reader.useDelimiter("\\,|\\n");
while(reader.hasNext()) {
System.out.println(reader.next());
System.out.println(reader.next());
System.out.println(reader.nextDouble());
System.out.println(reader.nextInt()); //InputMismatchException
}
}
catch(IOException e) {
}
finally {
reader.close();
}
}
When I run the code, I get the following output:
137B245
1/4" bolt
0.59
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)
at lab02d.inputFile(lab02d.java:25)
at lab02d.main(lab02d.java:11)
parts.dat contains:
137B245,1/4" bolt,.59,12
137N245,1/4" nut,.29,12
137B246,1/2" bolt,.79,12
137N246,1/2" nut,.39,25
139S128,1/8" wood screw,.19,8
139S129,1/4" wood screw,.22,4
139S130,1/2" wood screw,.35,16
145W321,1/8" washer,.12,5
145W322,1/4" washer,.14,6
145W323,1/2" washer,.18,9
I have tried several things to try to get this code to work. I have tried using Integer.parseInt(reader.next()), but that just throws another exception. I've also tried changing the text file encoding, but that didn't fix anything either.
Upvotes: 2
Views: 1083
Reputation: 2105
I'm fairly certain your file has additional white space at the end of those lines, preventing the scanner from parsing what looks like a reasonable int. Like a carriage return. Adjust your delimiter to something like below, and try again:
reader.useDelimiter("[\\,\\n\\r]+");
Upvotes: 1