Click here to Skip to main content
16,014,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I want to check an array's elements, if it smaller than 200 or lager than 800, it will add to array 1, and others will be added to array 2, array 1 and array 2 will be in a two dimensional arraylist, anyway it looks like this:

int[] arr = {171,100,809,70,365,239,37,821,791,452,349};

result:

result[0] = {171,100,809,70,37,821}
result[1] = {365,239,791,452,349}


And here is my code:

Java
import java.util.ArrayList;

public class twoDimen {

	public static void main (String[] args){
		int[] arr = {171,100,809,70,365,239,37,821,791,452,349};
		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
		
		for (int i = 0; i <= arr.length; i++){
			if (arr[i] < 200 || arr[i] > 800){
				result.get(0).add(arr[i]);
			}
			else
				result.get(1).add(arr[i]);		
		}
		
		System.out.println(result.get(0));
		System.out.println(result.get(1));
	}	
}


it does not show any errors before I execute it, but there's errors when executing it:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at twoDimen.main(twoDimen.java:11)

How can I fix it? And can I use dynamic two dimensional arrays instead of arraylist?

Thanks anyone's help.
Posted
Updated 10-Jan-13 23:33pm
v2

1 solution

You're doing result.get(0) before you've added any arrays to result.

Change this;
Java
ArrayList<arraylist><integer>> result = new ArrayList<arraylist><integer>>();
</integer></arraylist></integer></arraylist>


To this;
Java
ArrayList<arraylist><integer>> result = new ArrayList<arraylist><integer>>();
result.add(new ArrayList<integer>());
result.add(new ArrayList<integer>());
</integer></integer></integer></arraylist></integer></arraylist>



Hope this helps,
Fredrik
 
Share this answer
 
Comments
unbelievablename 11-Jan-13 6:05am    
Okay, thanks, I have done the changes, it does solve the "index:0, size:0" problem, but still has "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at twoDimen.main(twoDimen.java:12)",
what's the problem?
Fredrik Bornander 11-Jan-13 6:10am    
It's because you'r also doing
for (int i = 0; i <= arr.length; i++){
That line needs to be;
for (int i = 0; i < arr.length; i++){

/Fredrik
unbelievablename 11-Jan-13 8:21am    
Okay I see, thank you .
unbelievablename 11-Jan-13 8:22am    
Oh, and can I use arrays instead of arraylist?
Fredrik Bornander 11-Jan-13 9:21am    
Yes but with much more effort as an array won't resize as easily as an array list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900