简体   繁体   中英

Delimiting Scanner input from file

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"

Instead of relying on the input having exactly 8 records per line (currently you just call input.next() without checking if there actually is another token) you should use input.hasNext() to see if it has another token. This will allows you to see more gracefully when you receive a line that doesn't match what you are expecting and will help to debug this.

See http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

It's hard to see from your question the exact format of your input file, but I suspct something is wrong there. Maybe print out each line as it is processed, or catch the exception when it's thrown and print the line then. That will narrow down which bit of the input file, doesn't match your expectation.

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 with hasNext() before you call next() on the scanner object, that will prevent you from this exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM