我一直收到这个错误。我不确定原因是否是因为文本文档中包含的选项卡。但我无法弄明白!
输入文件:
Baker, William, Chavez, 04/01/05, 04/10/06
Sanchez, Jose, Chavez, 06/15/05,
Anderson, Robert, Wong, 04/02/05, 03/30/06
这是我的错误:
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)
这是我的readFile类的代码!无法弄清楚
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();
}
}
答案 0 :(得分:2)
我的猜测是你有一行多于或少于四个字。注意。如果你说
,Scanner.next()会读取一个单词one{tab}two three{tab}four{tab}five{newline}
这是五个字。一旦发生这种情况,您将无法获得四个单词的确切倍数,并且您的程序将会崩溃。
我建议您一次只读一行,然后仅使用制表符分割。
while (x.hasNextLine()) {
String line = x.nextLine();
if (line.trim().isEmpty()) continue; // skip blank lines.
String[] parts = line.split("\t", 4);
}