[英]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方法,但價值仍然像那樣。
之前謝謝。 。
如果希望記錄x
和xx
變量中的每個更改,則應將它們存儲在某些數據結構中。
例如,在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);
}
}
現在,您可以遍歷兩個列表以恢復循環中所有x
和xx
的值,或者僅打印整個列表:
System.out.println(xHistory);
System.out.println(xxHistory);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.