在Java中检查素数作为用户输入
我试图检查用户输入是否是质数。下面的代码是我的。这里怎么了在Java中检查素数作为用户输入,java,Java,我试图检查用户输入是否是质数。下面的代码是我的。这里怎么了 public static void main(String args[]) { int a; Scanner sc = new Scanner(System.in); System.out.println("Enter number to check : "); //sc.close(); for (a = sc.nextInt(); a > 2;) { bool
public static void main(String args[]) {
int a;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number to check : ");
//sc.close();
for (a = sc.nextInt(); a > 2;) {
boolean isPrime = true;
for (int b = 2; b < a; b++) {
if (a % b == 0) {
isPrime = false;
//System.out.println(a + " is not a prime number");
break;
}
if(isPrime) {
System.out.println(a + " is a prime number");
}
}
}
}
publicstaticvoidmain(字符串参数[]){
INTA;
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入要检查的编号:”);
//sc.close();
对于(a=sc.nextInt();a>2;){
布尔值isPrime=true;
for(intb=2;b
}将打印语句移出内部循环
public static void main(String args[]) {
int a;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number to check : ");
//sc.close();
for (a = sc.nextInt(); a > 2;) {
boolean isPrime = true;
for (int b = 2; b < a; b++) {
if (a % b == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println(a + " is a prime number");
} else {
System.out.println(a + " is not a prime number");
}
}
}
publicstaticvoidmain(字符串参数[]){
INTA;
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入要检查的编号:”);
//sc.close();
对于(a=sc.nextInt();a>2;){
布尔值isPrime=true;
for(intb=2;b
您的程序唯一调用的sc.nextInt()
出现在外部循环的初始化子句中。因此,在循环体的第一次迭代之前读取输入,而不再读取。因此,外部循环的每次迭代都会测试相同的a
,因此您要么无限循环,要么根本不循环
此外,正如@Gendarme在他的回答中指出的,您的内部循环中有一个
System.out.println()
。它应该被提升到外部,这样它只会在内部的所有迭代完成后打印,因此最终答案是已知的。为什么让我们猜测?为什么你认为有什么问题?它与两条打印线循环外部仍然是一个无止境的循环,因为它永远不会改变;)