shreekanth
shreekanth

Reputation: 489

Update variables in for loop in post increment

I am working on simple example.Initially taking the value of a as 1 and b as 2. I am calling method to do an update, when I print this a and b. It will be 1 and 2 as expected. But I should update this a and b in each loop, How can I do this?I am getting thought of returning as list. Is there a simple way to accomplish it?

public class UpdateTest {

    public static void main(String[] args) {
        int a=1;
        int b=2;
        for (int i = 0; i < 5; i++) {
            update(a,b);
        }

       System.out.println(a+"------"+b);
    }

    private static void update(int a, int b) {
        // TODO Auto-generated method stub
        for (int i = 0; i < 10; i++) {
            a++;
            b++;
        }
    }

}

Upvotes: 1

Views: 1018

Answers (2)

ParkerHalo
ParkerHalo

Reputation: 4430

Its not very nice but will do the job: You can simply return an array containing the values of a and b.

public class UpdateTest {

    public static void main(String[] args) {
        int a=1;
        int b=2;
        for (int i = 0; i < 5; i++) {
            int[] ret = update(a,b);
            a = ret[0];
            b = ret[1];
        }

        System.out.println("a= " + a + ", b= " +b);
    }

    private static int[] update(int a, int b) {
        for (int i = 0; i < 10; i++) {
            a++;
            b++;
        }
        int[] ret = {a,b};
        return ret;
    }
}

Upvotes: 1

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

You can put the values in a class e.g.

class Pair {
    int a, b;
    Pair(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

Initialize it like this

Pair pair = new Pair(1, 2);

Then modify the update method accordingly

private static void update(Pair pair) {
    for (int i = 0; i < 10; i++) {
        pair.a++;
        pair.b++;
    }
}

Upvotes: 2

Related Questions