【发布时间】:2013-10-20 21:48:26
【问题描述】:
我有一个检查素数然后显示它们的 java 代码。但是,在某些情况下没有素数(例如 14 - 17 之间)。在这些情况下,我希望显示一条消息。例如"No primes found"。我不知道如何将它添加到我的代码中。
这是我的整个班级:
import java.io.*;
public class Prime {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public static int lowerBound;
public static int higherBound;
public void getInput() throws IOException {
System.out.println("Please enter the lower and upper bound");
String line1 = input.readLine();
String line2 = input.readLine();
int lowInput = Integer.parseInt(line1);
int highInput = Integer.parseInt(line2);
lowerBound = lowInput;
higherBound = highInput;
}
public void validatedata() throws IOException {
do {
getInput();
if (lowerBound < 2) {
System.out.println("Finish");
break;
} else if (higherBound < lowerBound) {
System.out
.println("The upper bound should be at least as big as the lower bound.");
}
} while (higherBound < lowerBound);
}
public void prime_calculation() throws IOException {
while ((lowerBound >= 2) && (higherBound > lowerBound)) {
int k;
for (k = lowerBound; k < higherBound; k++) {
boolean primecheck = true;
for (int j = 2; j < k; j++) {
if (k % j == 0) {
primecheck = false;
}
}
if (primecheck)
System.out.println(k);
}
validatedata();
}
}
}
这是我主要的 void 方法:
import java.io.IOException;
public class PrimeUser extends Prime {
public static void main(String argv[]) throws IOException {
Prime isprime = new Prime();
isprime.validatedata();
isprime.prime_calculation();
}
}
【问题讨论】:
-
好的,我喜欢你的作品,我知道这是你的第一篇文章,但你能展示整个班级吗?我可以回答这个我只需要看到整个班级。
-
我会在 for 循环之外添加一个布尔变量(我们称之为
primesInRange),初始化为 false。然后,如果 for 循环以primecheck仍然为真,则通过将 if 语句更改为if (primecheck) { System.out.println(k); primesInRange = true; }将primesInRange设置为真。然后,如果在检查完所有数字后primesInRange仍然为假,则没有找到素数,您就会知道打印出一条消息。 -
另外,作为一个小优化,你只需要从
j = 2循环到j <= k / 2。对于所有数字,没有任何因子大于n / 2,因此无需检查每个小于它的数字。
标签: java math primes prime-factoring