I have a program that reads input from a file. I am trying to delimit input to only return tokens after a comma. But it doesn’t seem to work. Here’s my code so far:
package usegradebook;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class GradeBook {
private static Object[][] studentRecords = new Object[8][8];
public void compileRecord() throws FileNotFoundException
{
File file = new File("SomeData.txt");
Scanner input = new Scanner(file);
input.useDelimiter(",");
for(int row = 0; row < studentRecords.length; row++)
{
for(int column = 0; column < studentRecords[row].length; column++)
{
studentRecords[row][column] = input.next();
}
}
input.close();
}
Here is the data:
LastName,FirstName,Exam1, Asg1, Asg2, Exam2, Asg3, Asg4
Karr, Arlen, 91, 86, 94, 100, 98, 93
Stotz, Ralph, 81,83,,93, 78
Yi, Yu, 99, 88, 101, 76, 90, 94
Rao, Sista, 91, 86, 94, 100, 98, 93
Christopher, Thomas, 78, 79, 82, 88, 78, 91
McClurg, Andrew, 91, 87, 99, 87,,93
Noble, Rich, 84, 79, 85, 88, 90, 91
Johnson, Mark, 100, 100, 100, 100, 100, 100
It returns a “Exception in thread “main” java.util.NoSuchElementException”
The problem is with input. It is missing 1 data for one of the record. So when it comes to the last record’s last data you will end up calling
input.next()when there is no data. Also make sure you check withhasNext()before you callnext()on the scanner object, that will prevent you from this exception.