0

The PrimeDetector class shown below has documentation which describes the uses of each method. The tester class creates an object of the PrimeDetector class and attempts to print a set of generated integer values from an ArrayList returned from the hasPrime() method. I do not see my error, as I have created a procedural version of it which works just fine. It prints only the first 3 prime numbers, and returns as having only detected 3 prime numbers--leading me to believe that the issue lies within the PrimeDetector class, somewhere within the for-loop, though I can't be certain, as it is nearly the same structure as my procedural version--so far as I can tell. I will include the single procedural class, as well as the OOP version and its tester.

/**
 * The PrimeDetector class detects prime numbers within a user's
 * given set [0,n] where n is a user-given upper limit.
 * 
 * @author A. Mackey
 * @version 06/05/14
 */
import java.util.*;
public class PrimeDetector {
    private int n;
    private int primeCounter;
    private ArrayList<Integer> primeList = new ArrayList<Integer>();

    /**
     * Constructor for objects of class PrimeDetector
     * @param n is the upper limit in the set [0,n] tested with the hasPrime() method.
     */
    public PrimeDetector(int n) {
        this.n = n;
    }

    /**
     * @return an ArrayList of type Integer containing all prime values within the set [0,n].
     */
    public ArrayList<Integer> hasPrime() {
        primeCounter = 0;
        for (int i = 1; i <= n; i++) {
            boolean isPrime = true;
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primeCounter++;
                primeList.add(i);
            } else {
                break;
            }
        }
        return primeList;
    }

    /**
     * @return primeCounter variable which holds and integer value equivalent to the number of prime values in
     * the [0,n] set evaluated in the hasPrime() method.
     */
    public int getPrimeCounter() {
        return primeCounter;
    }
}

Tester:

/**
 * The PrimeDetectorTest class tests the PrimeDetector class, which detects prime numbers within a user's
 * given set [0,n] where n = a user-given upper limit.
 * 
 * @author A. Mackey
 * @version 06/05/14
 */
import java.util.*;
public class PrimeDetectorTest
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a positive integer you wish to find primes up to: ");
        int n = in.nextInt();
        System.out.println("The following list is prime within the range [0, " + n + "]: ");
        PrimeDetector list = new PrimeDetector(n);

        ArrayList<Integer> primeList = list.hasPrime();

        for (int s : primeList)
        {
            System.out.println(s + " is prime.");
        }

        System.out.println(list.getPrimeCounter() + " prime numbers within this set.");
    }
}

Procedural version:

import java.util.*;
public class PrimeDetectorV1
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a positive integer you wish to find primes up to: ");
        int n = in.nextInt();
        int primeCounter = 0;
        System.out.println("The following list is prime within the range [0, " + n + "]: ");

        for(int i = 0; i <= n; i++)
        {
            while (i>0)
            {
                boolean isPrime = true;
                for (int j = 2; j <= i/2; j++)
                {
                    if(i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    System.out.println(i + " is prime.");
                    primeCounter++;
                    break;
                }
                else
                {
                    break;
                }
            }
        }
        System.out.println("There are " + primeCounter + " prime numbers within this set.");
    }
}

1 Answer 1

2
  if (isPrime) {
      primeCounter++;
      primeList.add(i);
  } else {
       break;
  }

Remove the else{break;} here. Because if you found a number that is not prime, you still need to check the next one. Currently your program will stop when it founds a number that is not prime.

Also 1 is not a prime number so you should start your first loop at 2.

Sign up to request clarification or add additional context in comments.

7 Comments

Hey, good on ya mate. Works perfectly. Care to expand on the logic behind that error a bit more? So the break causes it to stop when finding a number not prime, but--I would expect it to begin searching the next value of i for primality.
@alx The break; will cause the loop for (int i = 2; i <= n; i++) { to stop. So yes let's say you want to find the prime numbers in [2, 5] when you'll test 4, you'll found that it's not prime, setting isPrime to false and breaking the outer loop. You could use continue; instead to tell ok continue the loop for the next step without caring of what is after the statement, but I don't recommend to do this. Just remove the else.
I'm mainly curious--as it doesn't at all break my procedural version.
@alx Because in your procedural version you are breaking the while, not the outer for. So you keep go to the next number to check (actually your while is useless because you never decrement i inside it, you just add another layer of looping and you'll have to break the infinite loop you created).
I'm a bit new to the use of break--why does it not negatively affect the looping process in the if statement, but does in the else--and why was it non-affective in my procedural version?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.