Here is my assignment:
Here are the other classes I am using:
I am receiving a NullPointer on line 53: regularNumbers.enqueue(i);
But, I am not sure why. Additionally, I need to display my results 12 primes per line, and a space between each. Suggestions? Thanks all for taking the time to read my post.
Here is my code:
import java.util.*;
public class Sieve {
private Queue<Integer> regularNumbers;// = new LinkedQueue<Integer>();
private Queue<Integer> primeNumbers;// = new LinkedQueue<Integer>();
private boolean hasResults = false;
private Integer firstNumber;
private int max;
private int count = 1;
/*
* Default Sieve is created in this constructor.
*/
public Sieve(){
Queue<Integer> regularNumbers = new LinkedQueue<Integer>();
Queue<Integer> primeNumbers = new LinkedQueue<Integer>();
//primeNumbers = null;
//regularNumbers = null;
}
/*
* This method uses the "Sieve of Eratosthenes" algorithm to compute a list
* of prime numbers ranging from 2 to the user defined maximum n.
*/
public void computeTo(int n)
{
/*
* This boolean is used to see whether or not the computeTo method has
* been called and will be used in future methods for IllegalStateExceptions.
*/
hasResults = true;
max = n;
/*
* Illegal argument exception is thrown when the integer is less than 2.
*/
if ( n < 2){
throw new IllegalArgumentException("Must be 2 or greater");
}
/*
* This for loop is used to add all numbers ranging from 2 to its max (n),
* which will be provided by the user to the queue "regularNumbers"
*/
for(int i = 2; i < n; i++ ){
regularNumbers.enqueue(i);
}
do {
Queue<Integer> tempQueue = new LinkedQueue<Integer>();
Iterator<Integer> iterator = regularNumbers.iterator();
firstNumber = regularNumbers.dequeue();
if(firstNumber != null){
primeNumbers.enqueue(firstNumber);
//while(regularNumbers.peek() != null){
for(int i = 0; i < regularNumbers.size(); i++){
Integer secondNumber = regularNumbers.dequeue();
if(secondNumber % firstNumber != 0){
tempQueue.enqueue(secondNumber);
}
}
//primeNumbers = regularNumbers;
regularNumbers = tempQueue;
}
}
while(firstNumber < Math.sqrt(n));
}
public void reportResults(){
if(!hasResults){
throw new IllegalStateException("Primes need to be computed before calling this method.");
}
System.out.print(primeNumbers);
}
public int getMax(){
if( !hasResults ){
throw new IllegalStateException("Primes need to be computed before calling this method.");
}
return max;
}
public int getCount(){
if( !hasResults ){
throw new IllegalStateException("Primes need to be computed before calling this method.");
}
return count;
}
}