0

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);
            }
        }
    }
}
1
  • 1
    try with for(int i=0; i < a.length -1; i++) Commented Feb 14, 2014 at 6:50

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.