问题
I'm making a program to find prime numbers. I'm storing the prime numbers and all positive integers (right now till 100) in two ArrayList<Integer>
. Here's the code:
import java.util.ArrayList;
public class PrimeNumbers {
static ArrayList<Integer> num = new ArrayList<Integer>();
static ArrayList<Integer> prime = new ArrayList<Integer>();
public static void main(String[] args) {
prime.add(2);
prime.add(3);
prime.add(5);
for (int z = 1; z<=100; z++){
num.add(z);
}
outer: for (int a = 1; a <=num.size(); a++){
inner: for (int b = 1; b <=prime.size(); b++){
if (num.get(a)%prime.get(b) != 0){//line 14
if (prime.indexOf(b)+1 == prime.size()){
prime.add(a);
continue outer;
}
else
continue inner;
}
else
continue outer;
}
}
System.out.println(prime);
}
}
But when I run the program, these errors show up:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429) at PrimeNumbers.main(PrimeNumbers.java:14)
What is going wrong?
回答1:
List indices run from 0 to size()-1
, but you are looping from 1 to size()
.
回答2:
The first element of a Collection
has index 0
, not 1
. Thus for example, accessing the third element should be done as collection.get(2)
.
Your loops should iterate like follows:
outer: for (int a = 0; a < num.size(); a++){
inner: for (int b = 0; b < prime.size(); b++){
...
}
}
Note the strict (<
) index comparison. Moreover, there is the following simpler way:
outer: for (Integer numItem : num){
inner: for (Integer primeItem : prime){
...
}
}
This for
loop form iterates on the whole collection.
回答3:
Try using Double instead of Integer. (Note how Double is an Object with a capital "D").
来源:https://stackoverflow.com/questions/27581220/arraylist-indexoutofbounds-exception-issue