Question

When i give the following input via stdin:

4 1 1 1 1 0 0 0 0

It throws 'run time error signal -1' instead of printing 'No Zeros'

Why is this happening ? I have used online Ideone compiler to run the code.

class FindZeroCount
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc=new Scanner(System.in);
        int size=sc.nextInt();
        //sc.nextLine();
        int input[]=new int[size];

        for(int i=0;i<size;i++)
            if(sc.hasNextInt())
                input[i]=sc.nextInt();
            else
                System.out.println("Not enough inputs given");

        int zi=findFirstZero(input,0,size-1);
        if(zi==-1)
            System.out.println("No zeros");
        System.out.println("Number of zeros = "+ (size-zi));

    }
    public static int findFirstZero(int input[],int l,int h)
    {
        int mid;
        if(h>=l)
        {
            mid=l + (h-l)/2;
            if((mid==0 || input[mid-1]==1) && input[mid]==0)
                return mid;
            else if(input[mid]==1 && input[mid+1]==0)
                return mid+1;
            else if(input[mid]==1)
                return findFirstZero(input,mid+1,h);
            else
                return findFirstZero(input,l,mid-1);

        }
        return -1;

    }
}
Was it helpful?

Solution

You get an ArrayIndexOutOfBoundsException when running the code with input as stated in your question: On your third recursive call you have l = 3, h = 3 and thus mid = 3. When the code enters your second if-statement (else if(input[mid]==1 && input[mid+1]==0)) you are trying to access index number 4, but your array's index only goes from 0 to 3.

Try stepping through your code with the debugger: Put a break point at the line int zi=findFirstZero(input,0,size-1); and step through it line by line!

However, I was not able to enter the entire sequence of numbers you gave above, since your first number (i.e. 4) tells how many numbers you can enter. When I enter 4 as the first number the code will start evaluating the sequence given after I enter the fourth 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top