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). 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. 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.