Hello I have a text file which I am trying to read a set of numbers from, this file looks similar to this:
st:ATTR1 20121011 0 0 127 122 -17
Im attempting to use a scanner, using the space as the delimiter, and read the first string, and the rest as ints. but whenever I try to run it I get this error:
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 prog8.prog8.main(prog8.java:22)
Im not sure why this is, because as far as I’m aware this should just allow me to read the next int, without worrying about other characters.
My code is:
package prog8;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class prog8 {
public static void main(String[] args) {
File file = new File("files/Weather.txt");
int date = 0;
int prcp = 0;
int snow = 0;
int snwd = 0;
int tmax = 0;
int tmin = 0;
try {
Scanner reader = new Scanner(file).useDelimiter(" ");
while (reader.hasNextLine()) {
String station = reader.next();
date = reader.nextInt();
prcp = reader.nextInt();
snow = reader.nextInt();
snwd = reader.nextInt();
tmax = reader.nextInt();
tmin = reader.nextInt();
System.out.printf("station: %s, date: %d, prcp: %d, snow: %d, snwd: %d, tmax: %d, tmin: %d", station, date, prcp, snow, snwd, tmax, tmin);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
can anyone tell me why this would be happening?
You can’t use multiple spaces if you’ve set the delimiter to be a single space.
Remove the
.useDelimiter(" ");and your program works fine