简体   繁体   English

神秘的Java运行时错误

[英]Mysterious Java Runtime Error

I wrote a very short program for an easy programming competition problem with an online judger (http://acm.sgu.ru/problem.php?contest=0&problem=184) but for some reason I was getting a runtime error on the 21st test (it doesn't specify what exactly the runtime error is). 我为在线裁判(http://acm.sgu.ru/problem.php?contest=0&problem=184)编写的一个简单的编程竞赛问题编写了一个很短的程序,但是由于某种原因,我在21号遇到了运行时错误测试(它没有指定确切的运行时错误)。 So I rewrote the code and it now does not give a runtime error, but I can't figure out why this code should work while the original did not. 因此,我重写了代码,现在它没有给出运行时错误,但是我无法弄清楚为什么该代码应该起作用而原始代码却不起作用。 Here is the working code: 这是工作代码:

Scanner scan = new Scanner(System.in);
int[] arr1 = new int[3];
int[] arr2 = new int[3];
for (int i = 0; i <= 2; i++) arr1[i] = scan.nextInt();
for (int i = 0; i <= 2; i++) arr2[i] = scan.nextInt();
System.out.println(Math.min(arr1[0]/arr2[0], Math.min(arr1[1]/arr2[1], arr1[2]/arr2[2])));

Here is the nonworking code: 这是无效的代码:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] arr1 = in.readLine().split(" ");
String[] arr2 = in.readLine().split(" ");
int flour = Integer.parseInt(arr1[0])/Integer.parseInt(arr2[0]);
int milk = Integer.parseInt(arr1[1])/Integer.parseInt(arr2[1]);
int cabbage = Integer.parseInt(arr1[2])/Integer.parseInt(arr2[2]);
System.out.println(Math.min(cabbage, Math.min(flour, milk)));

I at first tried changing the BufferedReader to Scanner in the nonworking code and using in.nextLine() but that didn't work. 首先,我尝试在不工作的代码中将BufferedReader更改为Scanner并使用in.nextLine(),但这没有用。 I then thought maybe there was a division by zero going on but the problem conditions preclude it and that should still be a problem in the working code, so I'm at a loss as to why the first works but the second does not. 然后我以为可能除数为零,但是问题条件排除了它,并且在工作代码中仍然应该是一个问题,所以我迷惑不解为什么第一个有效,而第二个无效。

It fails when the input is just separated by spaces without any line breaks. 当输入仅由空格分隔而没有任何换行符时,它将失败。 You get a NPE in the non-working code or when waiting for input then you exceed the timelimit of 0.5s for this test since your program blocks. 在非工作代码中或在等待输入时,您会得到一个NPE,由于程序被阻塞,因此您超出了此测试的时间限制0.5s。

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

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