我正在尝试在循环内使用scanner.nextLine()
,但出现异常。
问题位于代码的这一部分。
while(!sentence.equals("quit")){
dealWithSentence(sentence, voc);
System.out.println("Enter your sentence:");
sentence = scanner.nextLine();
}
有一个例外:
线程“主”中的异常java.util.NoSuchElementException:找不到行
在java.util.Scanner.nextLine(未知来源)
位于il.ac.tau.cs.sw1.ex4.SpellingCorrector.main(SpellingCorrector.java:34)
那是我完整的方法代码:
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
String filePath = scanner.nextLine();
if (filePath.contains(" ")){
scanner.close();
throw new Exception("[ERROR] the file path isnt correct");
}
File file = new File(filePath);
String[] voc = scanVocabulary(new Scanner(file));
if (voc == null)
{
scanner.close();
throw new Exception("[ERROR] the file isnt working");
}
System.out.println("Read " + voc.length + " words from " + file.getName());
System.out.println("Enter your sentence:");
String sentence = scanner.nextLine();
while(!sentence.equals("quit")){
dealWithSentence(sentence, voc);
System.out.println("Enter your sentence:");
sentence = scanner.nextLine();
}
scanner.close();
最佳答案
Scanner.nextLine()的工作方式如下。
String s = "Hello World! \n 3 + 3.0 = 6.0 true ";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// print the next line
System.out.println("" + scanner.nextLine());
// print the next line again
System.out.println("" + scanner.nextLine());
// close the scanner
scanner.close();
}
这将为您提供以下输出
Hello World!
3 + 3.0 = 6.0 true
因此,基本上,它开始扫描并跳过直到第一个新行字符,然后返回到目前为止已跳过的内容。在您的情况下,如果您只有一个句子而根本没有换行(\ n),它将跳过整个长度,并且永远找不到新行。从而抛出异常...在句子中间添加新的换行符,看看异常是否消失
学分至:http://www.tutorialspoint.com/java/util/scanner_nextline.htm