内部 while 循环变量 j 在递增后保持为 3,而在下一次迭代时应该为 1。因此,内部 while 条件失败并被终止,输出仅为 2,而不是 2、3、5。
public static void main(String[] args) {
int i=2;
int j=1;
int count=0;
while(i<=5)
{
while(j<=i)
{
if(i%j==0)
{
count++;
}
j++;
}
if(count==2)
System.out.println(i);
i++;
}
每次执行外循环时,您都需要重置内循环变量
j
和 count
:
public static void main(String[] args) {
int i = 2;
while (i <= 5) {
int j = 1;
int count = 0;
while (j <= i) {
if (i % j == 0) {
count++;
}
j++;
}
if (count == 2) {
System.out.println(i);
}
i++;
}
}