Reputation: 105
I keep getting this error. I wasn't sure if the reason was because of the tabs that are contained within the text document. But I can't figure it out!
input file:
Baker, William, Chavez, 04/01/05, 04/10/06
Sanchez, Jose, Chavez, 06/15/05,
Anderson, Robert, Wong, 04/02/05, 03/30/06
Here is my error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at readFile.readFile(readFile.java:26)
at Tree.main(Tree.java:64)
Here is my code for my readFile class! Can't figure it out
import java.io.*;
import java.util.*;
public class readFile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("patient.txt"));
}
catch (Exception e){
System.out.println("Couldn't find file!");
}
}
public void readFile(){
Tree tree = new Tree();
{
int key=0;
while(x.hasNext()){
String patientName = x.next();
String doctorName = x.next();
String currentApp = x.next();
String nextApp = x.next();
tree.addNode(key++, patientName, doctorName, currentApp, nextApp);
}
}
}
public void closeFile(){
x.close();
}
}
Upvotes: 0
Views: 2899
Reputation: 533820
My guess is you have a line which more or less than four words. Note. Scanner.next() reads a word so if you have say
one{tab}two three{tab}four{tab}five{newline}
This is five words. Once this happens you won't have an exact multiple of four words and your programs will crash as it does.
I suggest you read a line at a time and split using just the tab character instead.
while (x.hasNextLine()) {
String line = x.nextLine();
if (line.trim().isEmpty()) continue; // skip blank lines.
String[] parts = line.split("\t", 4);
}
Upvotes: 2