线程“main”java.util.NoSuchElementException,Java扫描程序中的异常

时间:2018-03-06 07:50:30

标签: java

我知道关于这个话题有几个问题,我找不到我理解的答案。

我有以下代码:

import java.util.Scanner;
public class Train
{
 public static void main (String [] args)
 {
  Scanner scan = new Scanner (System.in);
   System.out.println("Please enter 4 integers ");
   System.out.println("Please enter the speed of train 1: ");
   int v1 = scan.nextInt();
   System.out.println("Please enter the time of train 1: ");
   int t1 = scan.nextInt();
   System.out.println("Please enter the speed of train 2: ");
   int v2 = scan.nextInt();
   System.out.println("Please enter the time of train 2: ");
   int t2 = scan.nextInt();

   int d1 = v1*t1;
   int d2 = v2*t2;

   System.out.println(Math.abs(d1-d2));
 }
}

生成以下日志:

Please enter 4 integers 
Please enter the speed of train 1: 
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at Train.main(Train.java:9)

请帮我找到错误并修复它。提前致谢! URI

1 个答案:

答案 0 :(得分:1)

Scanner抛出java.util.NoSuchElementException,以防在尝试读取下一个令牌时遇到输入结束。 您可以使用^ D(Linux)或^ Z(Windows)

重现它

如果在扫描仪可以读取之前关闭输入流,也会发生这种情况。

你不能解释你是如何运行程序的(IDE?console?),但看起来它出现在第一次阅读时(我猜)System.in已经关闭。