在循环外部和内部设置初始值

Cha*_*Lee -8 java loops

我想知道设置这样的代码之间的真正区别

public boolean stringE(String str) {
  int count = 0;
  for (int i =0; i < str.length(); i++) {     
     if (str.charAt(i) == 'e') {
         count += 1;
     }
  }
  return (count >=1 && count<=3 );
}
Run Code Online (Sandbox Code Playgroud)

还有这个

public boolean stringE(String str) {
  for (int i =0; i < str.length(); i++) {
    int count = 0;     
    if (str.charAt(i) == 'e') {
      count += 1;
    }
  }
  return (count >=1 && count<=3 );
}
Run Code Online (Sandbox Code Playgroud)

我知道第一个是正确的但是通过在"for loop"中设置"int count = 0"会有什么不同.难道它还不会在count = 0中加1吗?

Era*_*ran 5

第二种情况不会编译,因为countreturn语句中不会被识别,因为在这种情况下count变量的范围只在for循环内部.

这就是你必须countfor循环之外声明的原因.

第二种情况的另一个问题,如Dici所提到的,是你在循环的每次迭代中重置count0,这意味着循环不计算它应该计算的数量.