Reputation: 7
I have a project which I need help fixing my code to read a text file into an array. My coding can open the file but gives me "NoSuchElementException" error when I get to this line, String contactInfo = inFS.nextLine().trim(); If I remake out the inner loop, it goes into an infinite loop.
Here are criteria for this project, my current coding and some sample data. Any suggestions are appreciated.
Method readContactsFromFile
The method will read the data from the text file “?????.txt”, each line in the file contains a first name, last name, and phone number separated by a comma. Hint: After reading each line, use the split function. The split function will read each field separated by a comma and place it into an array String contactInfo = input.nextLine().trim(); String[] contactInfoArray = contactInfo.split(",");
public static String[][] readContactsFromFile(Scanner scanner) throws IOException {
String [][] contactsArray = new String[MAX_SIZE][MAX_FIELDS];
String inputFileName;
String filename;
FileInputStream contactsStream = null; // File input stream
Scanner inFS = null; // Scanner object
// Try to open file
System.out.print("Enter file name: ");
inputFileName = scanner.next();
filename= inputFileName+".txt";
try {
contactsStream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
inFS = new Scanner(contactsStream);
while(inFS.hasNextLine()){
for(int row=0;row<MAX_SIZE;row++) {
String contactInfo = inFS.nextLine().trim();
String[] contactInfoArray = contactInfo.split(",");
for(int column=0;column<MAX_FIELDS;column++) {
contactsArray [row][column] = contactInfoArray[column];
}
}
}
return contactsArray;
}
Sample data from text file(without the additional line separating the records):
Emily,Watson,913-555-0001
Madison,Jacobs,913-555-0002
Joshua,Cooper,913-555-0003
Brandon,Alexander,913-555-0004
Emma,Miller,913-555-0005
Upvotes: 0
Views: 261
Reputation: 385
I noticed your code could be cleaned up with some help, as there is a lot of extra stuff, which may be causing confusion.
Scanner sc = new Scanner("Test.txt");
String line;
while(!(line = sc.nextLine()).equals("")){
String[] elems = line.split(",");
//implement the rest of the code
}
This will be able to do whatever you are trying to do with the code.
As pointed out, you read the line twice. Here, the
while(!(line = sc.nextLine()).equals(""))
takes care of that, by calling first storing the nextLine in the variable line, and then checking for null equality with null.
Upvotes: 0
Reputation: 3205
Looks like your file has less lines than MAX_SIZE. If you remove for(int row=0;row<MAX_SIZE;row++)
, create a variable row
and increment it in each iteration that would be one thing. You'd need to limit the loop further too while(inFS.hasNextLine() && row < MAX_SIZE)
about.
Upvotes: 1