package text;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
x = in.nextInt();
boolean isprime = true;
for (int i = 2; i <= x; i++) {
for(int j = 2; j < i; j++) {
if(i % j == 0) {
isprime = false;
break;
}
}
if(isprime) System.out.print(i + " ");
isprime = true; //这里为什么一定要重新赋值true?不赋值为什么没有运行结果?
}
}
}
The isprime variable can be regarded as a flag. In the program, it is decided whether to print i based on the last value of isprime. As for why the value is reassigned as you asked, this is to prepare for the next round of the loop. If the value of isprime is not initialized to true, then i cannot be printed even if i is a prime number.