繁体   English   中英

如何在Java中通过两个循环访问外部变量

[英]How to access variable outside with two looping in java

我有循环访问的变量。 但是有两个循环。

这是我的代码:

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

        }
    }

当我这样访问变量时,我就知道最后一个谁。

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

取值者是最后一个值。 如何在all循环之外访问变量以获取所有值? 反正有获取所有价值的机会吗? 我已经尝试使用getter和setter方法,但价值仍然像那样。

之前谢谢。

如果希望记录xxx变量中的每个更改,则应将它们存储在某些数据结构中。

例如,在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);
    }
}

现在,您可以遍历两个列表以恢复循环中所有xxx的值,或者仅打印整个列表:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM