I'm sorry for (another) admittedly quite basic question, but I'm having more problems in some Java code that I have to right for class. The assignment is to do a sieve of Eratosthenes program, and while my constructor seems to work (calling myArray[50]
from the main
method gives the value it was initialized to), it doesn't reflect any changes that the other classes were meant to make to myArray
. Also, print()
prints nothing (probably because the function sees an unitialized version of myArray
.).
The goal is that SieveEm() and deleteStuff() mark all of the non-primes as false, the print() comes by and prints all of the prime numbers(marked true).
I couldn't seem to find anything on the internet/StackOverflow addressing the problem. What am I doing wrong?
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]);
}
}