为什么程序在循环时跳过

0 java

为什么我的程序跳过while循环?

class DigitRepeat
{
  public static void main(String args[])
  {
      int n=133,dig=3,digit,count=0;

      while(n!=0)
      {
         digit=n%10;
         if(dig==digit)
         {
            count=count++;
         }
         n=n/10;
      }

      if(count==0)
          System.out.println("digit not found");
      else
          System.out.println("digit occurs "+count+" times.");
  }
}
Run Code Online (Sandbox Code Playgroud)

Nyb*_*ble 10

> count=count++;

应该

> count++;

解释:

> count=count++;

a_temp_var=count;
count=count+1;
count=a_temp_var;
等于:
a_temp_var=count;
count=a_temp_var;
等于什么都不做.

  • 解释一下:`count ++`是一个后增量.它首先将count的值赋给左侧然后递增.另一方面,你有预增量`++ count`,反之亦然.所以你/可以/写`count = ++ count`,但这不是好风格. (3认同)

Pet*_*rey 6

如果我查看我的IDE中的代码,它会发出警告

count++从未使用过更改的值.

即它警告我计算的值被丢弃.

如果我在调试器中单步执行代码,我可以看到循环执行但是行

count = count++;
Run Code Online (Sandbox Code Playgroud)

不会改变count.

你也想要

count++;

count+=1;

count=count+1;
Run Code Online (Sandbox Code Playgroud)

  • +1有关包括提及编译器/ IDE警告和使用调试器的真实解释.谁在乎什么答案最快? (2认同)