【发布时间】:2015-04-02 23:51:32
【问题描述】:
对于(另一个)公认的非常基本的问题,我很抱歉,但我在一些 Java 代码中遇到了更多问题,我必须在课堂上解决这些问题。任务是筛选 Eratosthenes 程序,虽然我的构造函数似乎可以工作(从 main 方法调用 myArray[50] 给出了它被初始化的值),但它没有反映其他类的任何更改旨在使myArray。此外,print() 不打印任何内容(可能是因为该函数看到了 myArray 的统一版本。)。
目标是 SieveEm() 和 deleteStuff() 将所有非素数标记为假,print() 来并打印所有素数(标记为真)。
我似乎在 Internet/StackOverflow 上找不到任何解决问题的方法。我做错了什么?
public class Sieve {
private int count;
private boolean[] myArray;
public Sieve(int length){
count = length+1;
boolean[] newArray = new boolean[length+1];
if(length>=1){
newArray[0]=false;
newArray[1]=false;
if(length>=2){
for(int i=0;i<=length;i++){
newArray[i]=true;
}
}
}
this.myArray = newArray;
}
public void SieveEm(){
System.out.println("here now");
System.out.println(this.myArray[50]==true);
for(int i=0; i<count;i++){
System.out.println("We got this far");
if(this.myArray[i]){
deleteStuff(i);
}
}
}
public void deleteStuff(int current){
int increment= current;
current+=increment;
while(current<count){
this.myArray[current]=false;
current+=increment;
}
}
public void print(){
this.SieveEm();
for(int i=2;i<count;i++){
if(this.myArray[i]){
System.out.println(i);
}
}
}
public static void main(String[] args){
Sieve mySieve = new Sieve(100);
mySieve.print();
System.out.println(mySieve.myArray[50]);
}
}
【问题讨论】:
-
你能解释一下“你期望发生的事情”和“正在发生的事情”之间的区别吗?
-
顺便说一句,但如果 SieveEm() 是一种方法,那么您应该以小写字母开头。