使用Java在循环中获取输入

时间:2015-11-13 08:47:12

标签: java input

我试图在循环中使用scanner.nextLine(),但我得到了一个例外。 问题出在代码的这一部分。

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

有例外:

  

线程中的异常" main" 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();

2 个答案:

答案 0 :(得分:4)

Scanner.nextLine()的工作原理如下..

-Source

这将为您提供以下输出

   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();
   }

所以基本上它开始扫描并跳过第一个新行字符,然后它返回它跳过的任何输出。在您的情况下,如果您只有一个句子而且根本没有新行(\ n),它将跳过整个长度,从不找到新行。从而抛出异常...在句子中间添加一个新的行字符,看看异常是否消失

致谢:http://www.tutorialspoint.com/java/util/scanner_nextline.htm

答案 1 :(得分:2)

在使用scanner.hasNextLine()之前检查scanner.nextLine()

if (scanner.hasNextLine()) {
  sentence = scanner.nextLine();
}

否则,扫描仪可能没有任何元素,也无法提供下一行

通常,您将在循环中读取输入,例如:

while (scanner.hasNextLine()) {
  System.out.println("Line: " + scanner.nextLine());
}