我对这个主要生成器类有一些问题。
这段代码又打印了一个素数。例如,当输入为 25 时,我得到了答案
2 3 5 7 11
13 17 19 23 29
(还有一个我不想要的额外素数 29)
我认为这是由于主类中的 --> while(primeGenerator.getCurrentPrime() < input) 。
但是如何确切地解决这个问题?
这些是我的代码片段
public class PrimeGeneratorTest {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
// ask for the input from the user
System.out.print("Enter the input: ");
int input = in.nextInt();
// create a prime generator object
PrimeGenerator primeGenerator = new PrimeGenerator(input);
// create a counter for the number of columns in a line
int n = 0;
// Check if the current prime number is less than the upper limit
while (primeGenerator.getCurrentPrime() < input){
System.out.printf("%-8d",primeGenerator.nextPrime());
n++;
//start a new line for each 5 columns
if (n % 5 == 0){
System.out.println();
}
}
}
}
这是 PrimeGenerator 类
public class PrimeGenerator {
private int upperLimit;
private int prime;
/**
* Constructs a prime generator object
* @param upperLimit the upper limit of the prime numbers
*/
public PrimeGenerator(int upperLimit){
this.upperLimit = upperLimit;
prime = 2;
}
/**
* Checks if the current iterating number is prime or not
* @return true if prime
* false if not prime
*/
public boolean isPrime(){
boolean isPrime = true;
for (int i = 2; i < prime ; i++){
if (prime % i == 0){
isPrime = false;
}
}
return isPrime;
}
/**
* Returns the next prime number
* @return the next prime number
*/
public int nextPrime(){
int currentPrime = 2;
while(!isPrime()){
prime ++;
}
currentPrime = prime;
prime ++;
return currentPrime;
}//nextPrime
/**
* Returns the current iterating prime number
* @return current iterating prime number
*/
public int getCurrentPrime() {
return prime;
}
}
提前致谢!
潇潇雨雨
慕盖茨4494581
相关分类