简体   繁体   English

Scanner.nextLine()上的NoSuchElementException

[英]NoSuchElementException on Scanner.nextLine()

I don't know why I keep getting this exception because I only have my scanner process the lines when it hasNext(). 我不知道为什么一直收到此异常,因为只有当我的扫描程序具有hasNext()时,我才对其进行处理。 It will print the lines but then throw this exception. 它将打印行,然后引发此异常。 Here is my code: 这是我的代码:

PagesCollection tester = new PagesCollection();

String fileName = (args.length >  0)? args[0] : "none";
Scanner scan = new Scanner(new FileInputStream(fileName), "UTF-8");

while (scan.hasNext()) {
  String line = scan.nextLine();
  line = line.replace("\n", "").replace("\r", "");
  System.out.println(line);
  Page newPage = new Page(line);
  tester.addPage(newPage);
}

Exception: 例外:

java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1516) 
at Webpage.countLines(Page.java:38) at Webpage.compareTo(Page.java:60) 
at Webpage.compareTo(Page.java:14) 
at java.util.Arrays.mergeSort(Arrays.java:1144) 
at java.util.Arrays.sort(Arrays.java:1079) 
at PagesCollection.addPage(PagesCollection.java:32) 
at PagesCollection.main(PagesCollection.java:75)

Since you get the same error when changing scan.nextLine to scan.next , looks like you might've stumbled across this bug[1]. 由于将scan.nextLine更改为scan.next时会遇到相同的错误,因此您可能偶然发现了该错误[1]。

It could be text in the file without "\\n" character. 它可以是文件中不含“ \\ n”字符的文本。 So, hasNext() is true but nextLine() doesn't exist. 因此,hasNext()为true,但nextLine()不存在。

Better use check hasNextLine() to be sure about next line. 最好使用check hasNextLine()来确定下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM