使用hasNextLine()但仍然得到java.util.NoSuchElementException:找不到行

我正在做一个编程项目并继续得到如下所示的错误。

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 

 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++; } } 

你正在阅读两行,只检查是否存在一行

这是第二次阅读

 String telno = read.nextLine(); //ArrayPhoneDirectory Line 42 

hasNextLine仅检查一行。 您正在尝试阅读两行。

 String name = read.nextLine(); String telno = read.nextLine(); 

在奇数行的情况下,可以为要读取的第二行抛出NoSuchElementException

一旦调用nextLine,指针就会递增。 因为,您之前已经在此行中调用过它:

 String name = read.nextLine(); 

所以,下次你试着在这里阅读它:

 String telno = read.nextLine(); 

你没有这样的元素例外。 你应该使用它:

 String telno = name 

你正在做的是在检查一行时读取太多行。 它是这样的:

问题

如果“行”上的数组如下所示:

 ["This is line 1"] 

然后read.hasNextLine()将返回true 。 然后输入你的while循环。 你运行的第一行是:

 String name = read.nextLine(); 

您从上面的数组中检索了一个元素,现在它看起来像这样:

 [] 

然后你继续你的while循环:

 String telno = read.nextLine(); 

然后nextLine()方法在数组中查找一个元素,为你提供,找不到任何元素,并抛出exception。