The default Scanner
delimiter is a space. So, one of your next()
calls is consuming the last name as well as the score (“Potter,72” for example). Hence, the nextInt()
call is failing.
Also, you seem to be trying to read four values when you have only two (considering the Scanner
is treating the last name and score as one). Select either a space or a comma as your delimiter. If you choose to have comma-separated values then use Scanner#useDelimiter(",")
as well.
Harry,Potter,72
Ron,Weasley,68
Considering the file format as above (csv) you can use the code below.
Scanner input = new Scanner(myFile).useDelimiter(",");
while (input.hasNextLine()) {
String[] line = input.nextLine().split(",");
String firstName = line[0];
String lastName = line[1];
int score = Integer.parseInt(line[2]);
System.out.println(firstName + " " + lastName + " " + score);
}
0
solved Can someone tell me what’s wrong with this java code?