when number < 3 will not enter the for loop, flag will still be true.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
int number = sc.nextInt();
boolean flag = true; //ture:质数。false:不是质数
for (int i = 2; i <= number-1; i++) {
if (number % i == 0 || number == 1) {
flag = false;
}
}
if(flag){
System.out.println(number + "是质数");
} else {
System.out.println(number + "不是质数");
}
}
}
< div class = "aw - list - img >
0 Answer
when number < 3 will not enter the for loop, flag will still be true.
1. Problem: your i value is 2, but the for loop is i< =number-1, you can see that the value of 1 and 2 will not enter into the for loop, so the value of flag will remain the same.
2, Solution: you can add if to judge whether the input value is 1 and 2 or other cases, if it is 1 and 2 or other direct output results, otherwise enter the loop to judge whether it is prime.
这家伙很懒,什么都没留下...