1

In my code i am comparing the 2 elements of an array. but i got the following exception.please can anybody help me

array:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Sarray.main(Sarray.java:64)


public class Sarray    
{    
        public static void main(String[] args)  
       {     



     Scanner scan = new Scanner(System.in); 
     System.out.print( "Enter sorted array length:" );
     int length = scan.nextInt();

     int[] a = new int[length];
     System.out.println("Enter integer sorted array:");      

     for(int i = 0;i<length;i++) 
     {
         String token = scan.next();
         a[i] = Integer.parseInt(token);         
     }       
     System.out.print("Unique array:");
     int[] b=new int[length];        
     int k=0;
     for(int i=0;i<length;i++)
     {  
        //here i got Exception              
         if(a[i] != a[i+1])
         {
             b[k++]= a[i];
         }
     }               
     for(int i=0;i<k;i++)
     {
         System.out.print(b[i]+" "); 
     }   
 }
}

4 Answers 4

3
 for(int i=0;i<length;i++)     

should be

 for(int i=0;i<length - 1;i++)

since you can have length - 1 number of comparisons.

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

Comments

2

When i == length -1 your i + 1 == length that is illegal. See a[i+1]

Comments

1

Your "i + 1" will go past the array bounds when you reach the last element.

Comments

-1

error arrives because value of i+1 is more than the array length.

instead of

for (int i=0; i<length; i++)

use

for (int i=0; i<length-1; i++)

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.