在 Java 中增加数组的值



为什么此代码不将"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]);
        }
    }
}

您没有增加数组值。进行

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

您增加的值用于声明的变量val,它是数组当前迭代索引变量的断开连接的副本。

最新更新