Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Java arrays (http://www.go4expert.com/forums/java-arrays-t9612/)

cyrow 25Mar2008 17:21

Java arrays
 
Code:

class Test{
        public static void main(String[] args){
                int x=0;
                int [] num = {1,1,3,3,3,3};
                int [] a = new int [4];
               
        for(int i = 0; i < num.length-1; i++){
          x  =++num[i];
          a[i++] = x;
                System.out.println("num :"+ i+"  " + x);
        }
       
       
        for (int j = 0; j< a.length; j++){
                System.out.println(a[j]);
        }
  }//end main
}//end class

/*
num :1 2
num :3 4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Test.main(Love.java:10)

Process completed.*/

Problem
I am going trought the array and counting all the elements which are the same. The answer given above is correct, 1 one occurs twice an 3 occurs 4 times. Why I am getting an out of bounds error?

harikrishna_sit 26Mar2008 17:16

Re: Java arrays
 
Quote:

Originally Posted by cyrow
Code:

class Test{
        public static void main(String[] args){
                int x=0;
                int [] num = {1,1,3,3,3,3};
                int [] a = new int [4];
               
        for(int i = 0; i < num.length-1; i++){
          x  =++num[i];
          a[i++] = x;
                System.out.println("num :"+ i+"  " + x);
        }
       
       
        for (int j = 0; j< a.length; j++){
                System.out.println(a[j]);
        }
  }//end main
}//end class

/*
num :1 2
num :3 4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Test.main(Love.java:10)

Process completed.*/

Problem
I am going trought the array and counting all the elements which are the same. The answer given above is correct, 1 one occurs twice an 3 occurs 4 times. Why I am getting an out of bounds error?

I could not find your logic correct. But I can say the reason for the exception. In the first for loop you are incrementing i value twice per iteration. So in the 3rd iteration i value will be 4. But when you say a[i++]=x; it will be a[4]=x; But the array a can have only 4 elements upto a[3]. That is the problem.


All times are GMT +5.5. The time now is 21:56.