NZEC runtime error in Java

2019-09-22 13:48发布

问题:

This is my code. Please check it where it is giving runtime exception. I wrote a piece of code to solve this problem.

I keep getting NZEC(runtime error), but I can't find which part of the code can cause any Exception since it only involves simple arithmetic computation (there should be no chance of divided by zero).

The logic of the code doesn't matter, and I just wonder where the exception could be hiding.

Any one can spot any bug? Thanks.

import java.io.BufferedReader;
import java.io.File; // headers
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
import java.math.BigInteger;

public class Mkequal // class
{
    public static void main(String[] args) throws IOException // main class
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System. in));
        Scanner sc = new Scanner(System. in );
        int t = Integer.parseInt(br.readLine());
        while (t-- > 0) // while loop
        {
            int sum = 0;
            int n = Integer.parseInt(br.readLine()); //number of elements in array
            int arr[] = new int[n];
            for (int i = 0; i < n; i++)
                arr[i] = sc.nextInt();
            for (int i = 0; i < n; i++)
                sum += arr[i];
            if (sum % n == 0) //if divisible by n,print n
                System.out.println(n);
            else
                System.out.println(n - 1);

        }
    }
}

回答1:

You are most probably creating too many memory in program. you must create array(arr) outside the while loop and manipulate it inside the loop..



回答2:

Probably, the int t = Integer.parseInt(br.readLine()); causes NumberFormatException (Integer.parseInt)

But you shold use your IDE's console (for example, here is Eclipse's console) to see the stacktrace - it will point you to the actual line where exception occurs