我正在做一个编程项目并继续得到下面显示的错误。
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at ArrayPhoneDirectory.loadData(ArrayPhoneDirectory.java:42)
at ArrayPhoneDirectoryTester.main(ArrayPhoneDirectoryTester.java:18)
我认为这是因为扫描程序read.nextLine()将超过文本文件的末尾。但是我使用了带有hasNextLine的while循环,所以我不确定为什么会这样。 谁知道我哪里出错?
public void loadData (String sourceName){
Scanner read = new Scanner(sourceName);
while (read.hasNextLine()) {
String name = read.nextLine();
String telno = read.nextLine(); //ArrayPhoneDirectory Line 42
add(name, telno);
}
}
相关文字文件
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
答案 0 :(得分:6)
您正在阅读两行,而只检查是否存在一个
这是第二次阅读
String telno = read.nextLine(); //ArrayPhoneDirectory Line 42
答案 1 :(得分:1)
hasNextLine
仅检查一行。您正在尝试阅读两行。
String name = read.nextLine();
String telno = read.nextLine();
如果行数为奇数,则可以为要读取的第二行抛出NoSuchElementException
。
答案 2 :(得分:0)
hasNextLine()
只会查看一个新行。检查一个后,你不能读两行。
如果您必须连续阅读记录,那么您可以
public void loadData (String sourceName){
Scanner read = new Scanner(sourceName);
int i = 1;
while (read.hasNextLine()) {
if(i%2 != 0)
String name = read.nextLine();
else
String telno = read.nextLine(); //ArrayPhoneDirectory Line 42
add(name, telno);
i++;
}
}
答案 3 :(得分:0)
一旦调用nextLine,指针就会递增。因为,您之前已在此行中调用过它:
String name = read.nextLine();
所以,下次你试着在这里阅读它:
String telno = read.nextLine();
你没有这样的元素异常。你应该改用它:
String telno = name
答案 4 :(得分:-1)
你正在做的是在检查一行时读取太多行。它是这样的:
如果“行”上的数组如下所示:
["This is line 1"]
然后read.hasNextLine()
将返回true
。然后输入while
循环。你运行第一行:
String name = read.nextLine();
您从上面的数组中检索了一个元素,现在它看起来像这样:
[]
然后继续while
循环:
String telno = read.nextLine();
然后nextLine()
方法在数组中查找一个元素,为你提供,找不到任何元素,并抛出异常。