最近在写Java作业,实现从文件输入,构成一个列表
代码如下:
public MyDlist (String f) {
......
else {
FileReader in = null;
try {
in = new FileReader(f);
Scanner sc = new Scanner(in);
String c = null;
// Checking if the next node is null or not.
while (!(c = sc.next()).isEmpty()) {//**********出错位置
DNode d2 = new DNode(null, null, null);
// Assigning string to node and add this node to list.
d2.setElement(c);
super.addLast(d2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
由于出错位置的代码问题,运行会出现以下错误:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at MyDlist.<init>(MyDlist.java:35)
at DlistTest.main(DlistTest.java:8)
后修改为
while (sc.hasNext()) {//**********出错位置
c = sc.next()
DNode d2 = new DNode(null, null, null);
即先判断还有无内容在文件中,再把值赋给c
来源:http://stackoverflow.com/questions/12874791/at-java-util-scanner-throwforunknown-source-error