【发布时间】:2014-09-08 20:23:13
【问题描述】:
我想知道设置这样的代码有什么真正的区别
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 );
}
还有这个
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 );
}
我知道第一个是正确的,但是通过在“for 循环”中设置“int count =0”会有所不同。它不会仍然将 1 添加到 count =0 吗?
【问题讨论】:
-
是的,但第二个示例中“count”的范围将被限制在 for 循环中。如果你正确地关闭了花括号,你可能会看到:)