Java:ArrayOutofBounds在尝试使用Sieve计算素数时出现异常
我的代码编译没有错误,但是在我的输出中,我得到了第37行的ArrayOutofBoundsException。除了主计数器外,其他一切都正常。有人能看出我在这段代码中犯了什么错误吗?主计数器在我的另一个程序中工作Java:ArrayOutofBounds在尝试使用Sieve计算素数时出现异常,java,sieve-of-eratosthenes,Java,Sieve Of Eratosthenes,我的代码编译没有错误,但是在我的输出中,我得到了第37行的ArrayOutofBoundsException。除了主计数器外,其他一切都正常。有人能看出我在这段代码中犯了什么错误吗?主计数器在我的另一个程序中工作 import java.util.Scanner; public class Sieve { public static void main(String[] args) { //get ceiling on our prime numbers int N;
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);
}
}
import java.util.Scanner;
公共类筛{
公共静态void main(字符串[]args){
//得到我们素数的上限
int N;
扫描仪sc=新的扫描仪(System.in);
System.out.print(“输入素数上限:”);
N=sc.nextInt();
sc.close();
//初始化我们的数字数组,其中true表示素数
布尔值[]isPrime=新布尔值[N];
isPrime[0]=假;
for(int c=1;c=2的素数
//首先循环,检查是否标记了数字
for(int i=2;i您的for循环条件不好
for (int c = 0; c <= N; c++) {
for(int c=0;c尝试c
而不使用=
。记住,数组在Java中是基于零的。这修复了它的一半,谢谢!但是,现在它说的是素数的数量等于N。有什么想法吗?还添加了素数解决方案
for (int c = 0; c < N; c++) {
for (int c = 1; c < N; c++) {
isPrime[c] = true;
}
Arrays.fill(isPrime, true);
isPrime[0] = false;
for (int x = 1, x < N; x++) {
for (int y = x; y < N; y+=x) {
isPrime[y] = false;
}
}