当if语句仅两次为真时,为什么for循环会发生3次?

时间:2018-09-07 14:57:04

标签: java for-loop if-statement

为什么我的代码在for循环内执行主体3次?

它不仅应该发生2次吗?

为什么3次?

运行此命令时,我得到:

“ 4除以2,其余为

0

4除以3,其余为

1

4除以4,余数为

0

循环已退出for循环,因为D现在为5 计数现在是2。

if语句应该发生2次的代码

N的值为4“

public class forIf {

public static void main (String[] args) {

int D;
int N = 4;
int count;

count = 0;

for (D = 2; D <= N; D++) {
  if (N % D == 0)
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
}
System.out.println("loop has exited out of for loop because D is now " + D);
System.out.println("count is now " + count + ". code inside if statement should've happend " + count + " times");
System.out.println("value of N is "+ N);
}
}
// shouldn't the code inside the if statement only happen twice?
// because N % D is only true twice?
// why is it running that block 3 times?

3 个答案:

答案 0 :(得分:1)

  

为什么我的代码在for循环内执行主体3次?

这是每次循环时的循环变量

int N = 4;
for (D = 2; D <= N; D++) ...

Loop 1: D = 2 , 2 <= 4 is true  
Loop 2: D = 3 , 3 <= 4 is true  
Loop 3: D = 4 , 4 <= 4 is true  

这就是循环发生三遍的原因。

为此,为什么

  

if语句应该发生2次的代码

正如其他人也指出的那样,如果要包含count++;,则if块内的唯一代码是println,则它们必须位于if块的括号内。

if (N % D == 0) { // <-- brace
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
} // <-- brace

答案 1 :(得分:0)

您的if只有一个语句count++。这两个打印语句不是其中的一部分。您需要将块放在{..}

for (D = 2; D <= N; D++) {
  if (N % D == 0) {
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
  }
}

答案 2 :(得分:0)

if(以及whilefor等)的内容超过一行时,您需要将它们括在方括号({})中。实际上,即使只是一行,您也应该始终这样做,因为这样做更容易阅读且不易出错。您的if应该看起来像这样:

for (D = 2; D <= N; D++) {
  if (N % D == 0) {
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
  }
}