Question

I did some research on this subject (I'm quite new to Java so excuse me my poor/incorrect wording) and I didn't find any related answers, so, here it goes.

I'm working on a program that can print prime numbers and I ran into following problem.

Here's the code:

public class pnumba {

    public static void main(String[] args) {

        int pnlimit = 100;
        System.out.println("Printing prime numbers");
        for (int numer = 2; numer <= pnlimit; numer++) {
            if (checkforprime(numer)) {
                System.out.println(numer);
            }

        }
    }

    public static boolean checkforprime(int numer) {
        for (int i = 2; i < numer; i++) {
            if (numer % i == 0) {
                return false;
            }
        }
        return true;
    }
}

My program prints all the prime numbers up to 100 and not 100 of them. My idea is to make an array to hold 100 prime numbers and break the loop when said array reaches its limit to fix this problem.

My questions are as following:

  1. How to make a loop that will fill up the array when my checkforprime() method returns true?
  2. Do I have to use break; to stop the loop when it reaches 100 prime numbers?
  3. Can I use <=arrayname.length to stop the for loop as an alternative?

Please tell me if you need more info.

Was it helpful?

Solution

Change your main block as follow:

int counter = 1;
System.out.println("Printing prime numbers");

for (int numer = 2; counter <= 100; numer++){
    if (checkforprime(numer)) {
        System.out.println(numer);
        counter++;
    }

}

Here Counter will help to execute your loop until 100 prime numbers are displayed...............!

OTHER TIPS

You are almost there already. Declare an array and fill it up for how many ever numbers you want in the main method instead of printing to screen. That will help you store in an array only as many prime numbers as you want.

public static void main(String[] args) {

    int counter = 0;
    int numberOfPrimes = 100;
    int[] primeArray = new int[numberOfPrimes];
    int arrayCounter = 0;
    System.out.println("Printing prime numbers");
    for (int numer = 2; numer <= counter; numer++) {

            if (checkforprime(numer)) {
                primeArray[arrayCounter] = numer;
                counter ++;
                arrayCounter ++;
        }

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top