任何人都可以解释以下两个程序之间的区别吗?他们看起来和我一样,但他们产生不同的输出。这是什么原因?
程序1:输出不正确的值; i=1
public class Test1{
public static void main(String[] args) {
int[] values = new int[] { 2, 3, 5, 1 };
int i = 0;
for (Integer integer : values) {
i =+ integer.intValue();
} // for loop ends
System.out.println("i=" + i);
}
}
程序2:输出期望值; i=11"
public class Test2{
public static void main(String[] args) {
int[] values = new int[] { 2, 3, 5, 1 };
int i = 0;
for (Integer integer : values) {
i = i + integer.intValue();
} // for loop ends
System.out.println("i=" + i);
}
}
最佳答案
显然,主要区别在于这一行:
i =+ integer.intValue();
也许它打算在第一个程序中使用i +=
而不是i =+
。
在您的版本中,第一个程序只是在每次迭代时分配一个值,因此它的最终结果是数组中的最后一个值(即 1
)。您的第二个程序执行它应该执行的操作 - 将数组中的所有元素相加,结果为 11
。
关于java - 基本 Java 问题 : equivalent integer arithmetic producing different results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17482786/