Java arrays

cyrow's Avatar, Join Date: Nov 2007
Go4Expert Member
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's Avatar, Join Date: Jan 2008
Newbie Member
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.