gpt4 book ai didi

java - 使用 Java 在循环中获取输入

转载 作者:行者123 更新时间:2023-11-29 06:56:09 25 4
gpt4 key购买 nike

我试图在循环中使用 scanner.nextLine(),但出现异常。问题出在这部分代码。

        while(!sentence.equals("quit")){
dealWithSentence(sentence, voc);
System.out.println("Enter your sentence:");
sentence = scanner.nextLine();
}

有异常(exception):

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at 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

关于java - 使用 Java 在循环中获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33688799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com