因此,我尝试打印1到100之间的质数,以及该范围内的总质数。我知道1到100之间的质数总数为25,但我想不出如何用Java打印出来。它保持打印7​​1?!?

谢谢您的帮助。

public class Chap6_Homework2 {
    public static void main (String [] args) {
        int i;
        int maxprime = 100;
        boolean isPrime = true;
        String foundprimenumbers = "";

        for (i = 2; i <= maxprime; i++) {
            isPrime = PrimeNumbers(i);
            if (isPrime) {
                foundprimenumbers = foundprimenumbers + i + " ";
            }
        }
    System.out.println("Prime numbers are " + foundprimenumbers);
    System.out.println("There are " + foundprimenumbers.length() + " prime numbers found.");
    }

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

    }



}

最佳答案

改成

int foundprimenumbers = 0;

for (i = 2; i <= maxprime; i++) {
      if (PrimeNumbers(i)) {
        System.out.println(i);
        foundprimenumbers++;
      }
}
// System.out.println("Prime numbers are " + foundprimenumbers);
System.out.println("There are " + foundprimenumbers + " prime numbers found.");


立即打印素数,素数的计数存储在int变量中

07-28 01:52