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.
You probably want something like this instead: