使用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。
- 如何从Retrofit onResponse()更新Activity / Fragment UI?
- 按一定数量排序列表?
- 将ArrayList 转换为byte
- java.lang.ClassNotFoundException:spring项目中的org.springframework.web.servlet.DispatcherServlet
- Android:getfromLocationName()在地址列表中返回大小0
- 覆盖方法和字段的不同行为
- Android O – 后台服务限制无法按预期工作
- Android:在Build中包含外部Jar(没有Eclipse)
- 如果已重新定义toString方法,如何打印对象的地址