【发布时间】:2014-11-18 21:19:26
【问题描述】:
我的代码编译没有错误,但在我的输出中,我得到了第 37 行的 ArrayOutofBoundsException。除了主计数器之外,一切正常。谁能看到我在这段代码中哪里出错了?主计数器在我的另一个程序中工作。
import java.util.Scanner;
public class Sieve {
public static void main(String[] args) {
//get ceiling on our prime numbers
int N;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the prime number ceiling: ");
N = sc.nextInt();
sc.close();
//init our numbers array, where true denotes prime
boolean[] isPrime = new boolean[N];
isPrime[0] = false;
for (int c = 1; c < N; c++) {
isPrime[c] = true;
}
//check every number >= 2 for primality
//first loops, checks to see is numbers are marked
for (int i = 2; i <= N; i++) {
if (isPrime[i-1]) {
System.out.print(i + " ");
//cross off all subsequent mutliples of
//second loop, marks all multiples of number
for (int j = i * 2; j <= N; j += i) {
isPrime[j-1] = false;
}
}
}
//counts primes
int primes = 0;
for (int c = 0; c <= N; c++) {
if (isPrime[c]); //error here
primes++;
}
//prints # of primes
System.out.println(" ");
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
【问题讨论】:
-
尝试不带
=的c < N。请记住,数组在 Java 中是从零开始的。
标签: java sieve-of-eratosthenes