Putra Nurfajar
Putra Nurfajar

Reputation: 11

How to access variable outside with two looping in java

I have variable that access in the looping . But there is two looping for.

Here is my code :

int x = 0;
int xx = 0;

    for (int d1 = 0; d1 < d - 1; d1++) {
        for (int d2 = d1 + 1; d2 < d; d2++) {

        //--other code---

        x = listt.indexOf(max);
        xx = list2.indexOf(max2);

        }
    }

When I access the variable like this , I got value who the last.

int x = 0;
int xx = 0;

    for (int d1 = 0; d1 < d - 1; d1++) {
        for (int d2 = d1 + 1; d2 < d; d2++) {

        //--other code---

        x = list.indexOf(max);
        xx = list2.indexOf(max2);

        }
    }
    System.out.println(" " + x);
    System.out.println(" " + xx);

The value who taken is the last value . How can I access the variable outside all loop to get all value ? Is there anyway to get all value ? I have tried with getter and setter method but value still like that.

Thanks before . .

Upvotes: 0

Views: 258

Answers (1)

Eran
Eran

Reputation: 393811

If you wish to record every change in the x and xx variables, you should store them in some data structure.

For example, in an ArrayList :

int x = 0;
int xx = 0;
List<Integer> xHistory = new ArrayList<>();
List<Integer> xxHistory = new ArrayList<>();

for (int d1 = 0; d1 < d - 1; d1++) {
    for (int d2 = d1 + 1; d2 < d; d2++) {

    //--other code---

        x = list.indexOf(max);
        xx = list2.indexOf(max2);
        xHistory.add(x);
        xxHistory.add(x);
    }
}

Now you can iterate over the two lists to recover all the values x and xx had during the loop, or simply print the whole lists :

System.out.println(xHistory);
System.out.println(xxHistory);

Upvotes: 3

Related Questions