Shirin
Shirin

Reputation: 53

Increasing Array's values in Java

Why this code doesn't add "1" to array's values? (I have written it by "Enhanced For Loop"; when I wrote it with "old For", it worked.

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]);
        }
    }
}

Upvotes: 1

Views: 1424

Answers (2)

vijay
vijay

Reputation: 494

The value you are increasing is for the declared variable val, which is disconnected copy of array's currently iterating index variable.

Upvotes: 1

deogratias
deogratias

Reputation: 480

You are not increasing array values.Do

public static void addOne(int[] list){
     for(int i=0;i<list.length;i++){
                list[i] = list[i] + 1;
         }
}

Below statement

val = val + 1;   //will not increase array value it will increase val value

Upvotes: 1

Related Questions