Java 在方法内的增强FOR循环末尾添加花括号的错误
我是java初学者。 我真的不明白,如果你像下面这样在for循环的末尾直观地添加了两个花括号,它为什么会失败,因此,根据目前获得的知识,这样做看起来是最正常和自然的Java 在方法内的增强FOR循环末尾添加花括号的错误,java,brackets,Java,Brackets,我是java初学者。 我真的不明白,如果你像下面这样在for循环的末尾直观地添加了两个花括号,它为什么会失败,因此,根据目前获得的知识,这样做看起来是最正常和自然的 public class ClassOne { public static void main(String[] args) { System.out.println(av(5, 6, 7)); } public static int av(int... numbers) {
public class ClassOne {
public static void main(String[] args) {
System.out.println(av(5, 6, 7));
}
public static int av(int... numbers) {
int total = 0;
for (int x: numbers) total = total += x;
return total / numbers.length;
}
}
你现在可以检查一下。添加花括号后失败:
for (int x: numbers) {
total = total += x;
return total / numbers.length;
}
如果有人能澄清,我将不胜感激。谢谢。不添加括号将只运行第一行。添加括号将使return语句在第一次迭代后运行。再次感谢。这意味着:对于int x:numbers total=total+=x;返回总数/numbers.length;等价于int x:numbers{total=total+=x};返回总数/numbers.length;其中for循环只处理分号之前的部分;忘了它后面是什么。很明显,要返回的值输出必须只有一个值,否则循环返回将输出不止一个值,这将造成混淆并导致错误。
public class ClassFour {
public static void main(String[] args) {
System.out.println(av(5, 6, 7));
}
public static int av(int... numbers) {
int total = 0;
for (int x: numbers) {
total = total += x;
return total / numbers.length;
}
}
}