循环为什么下面的代码不能正常工作?(爪哇)
我的目标是接收用户输入,并找出它是否是质数
“我花了好几个小时在这件事上,它几乎奏效了。然而,当我输入2或3时,我什么也得不到。do-while循环只是跳到下一个迭代
我创建的for循环不适用于2或3,因此我为此创建了一个单独的if语句。问题是,它不起作用。我不知道为什么,只知道它可能不会执行
import java.util.Scanner;
public class Lab4a {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in); //creates a Scanner that will receive user input
boolean isPrime = false; //this, in the end, is where the "primeness" of the input is stored
int num; //the variable which will store the user input
boolean isOver = false; //is true once the "primeness" of the input has been decided
do { //executes at least once
System.out.println("Enter a positive integer or 0 to exit:"); //prompts the user for input
num = scnr.nextInt(); //stores the input
if (num == 0) { //if the number is zero, the loop terminates; if it's negative, the loop terminates as well
System.exit(0);
} else if (num < 0) {
System.out.println("Please enter a positive integer.");
System.exit(1);
}
for (int mult = 2; mult <= num/2; mult++) { //divides the user input by 2, tests for if anything remains; increments by one up to the half of the number. If a remain is encountered,
// isPrime becomes false and isOver true and the for loop is terminated. If not, the for loop will end with isPrime true and isOver false
if (num % mult == 0) {
isPrime = false;
isOver = true;
break;
} else {
isPrime = true;
isOver = true;
}
}
if (num == 2 || num == 3) { //the for test above does not work if the user input is 2 or 3, so a separate if statement tests for that
isPrime = true;
}
} while (!isOver); //if isOver is true, the while loop ends
if (isPrime == true) { //prints the appropriate answer
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}
}
我通常会自己解决这些问题,但我又一次在这方面花了4个小时的时间,我还有另一个类似的程序要写,还有一个微积分测验要准备明天,在这个测验中我对杰克·拉什一清二楚。我真的很绝望
TL;DR:当我输入2或3时,程序不能正常工作;可能是因为if语句没有运行。除此之外,我一无所知
谢谢你的帮助
# 1 楼答案
为
for
循环for (int mult = 2; mult <= num/2; mult++)
设置限制时出现问题当输入为2
num/2
或3时,num/2
返回1,条件为运行vizmult<=2
失败