为什么这段代码不会为数组的值添加“1”? (我用“Enhanced For Loop”编写了它;当我用“old For”编写它时,它起作用了。
public class EnhanceForLoop {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("List before call addOne");
printList(list);
System.out.println("Calling addOne");
addOne(list);
System.out.println("List after call addOne");
printList(list);
}
public static void addOne(int[] list) {
for (int val : list) {
val = val + 1;
}
}
public static void printList(int[] list) {
System.out.println("index, value");
for (int i = 0; i < list.length; i++) {
System.out.println(i + ", " + list[i]);
}
}
}
答案 0 :(得分:1)
您没有增加数组值。
public static void addOne(int[] list){
for(int i=0;i<list.length;i++){
list[i] = list[i] + 1;
}
}
声明
val = val + 1; //will not increase array value it will increase val value
答案 1 :(得分:1)
您增加的值是声明的变量val
,它是数组当前迭代索引变量的断开副本。