amish3110
amish3110

Reputation: 11

Array exception in finding missing number

I have written a code for finding the missing number in series. Here, i am also getting correct result an missing number but with exception. The exception is arrayindexoutofboundsexception which is likely possible because i am increasing the length of array.

Code is below . Any help to remove that exception ...

import java.io.*;
class findarr
{
    public static void main(String args[]) throws IOException
    {
        int a[] = {10,12,14,16,20};
        int x,y,z;
        for(int i=0;i<a.length;i++)
        {
            z = a[i+1]-a[i];
            if(z!=2)
            {
                x = a[i]+2;
                y = a[i+1]-2;
                if(x==y)
                System.out.println(x);
            }
        }
    }
}

Upvotes: 0

Views: 135

Answers (2)

earthmover
earthmover

Reputation: 4525

You have to run your loop till a.length-1, like this:

for(int i=0;i<a.length-1;i++)
{
   z = a[i+1]-a[i]; //throws exception because of a[i+1]
   if(z!=2)
   {
        x = a[i]+2;
        y = a[i+1]-2;
        if(x==y)
        System.out.println(x);
   }
}

and you should break; your loop if (x==y)...

Upvotes: 0

Ronald
Ronald

Reputation: 2882

If i == a.length - 1 the expression z = a[i+1]-a[i]; will generate an ArrayOutOfBoundsException (since a[i+1] exceeds the array). Limit your loop by i < a.length - 1

Upvotes: 2

Related Questions