我正在尝试在for循环中获取当前i
值和先前的i
值。这可能吗?
public void mousePressed() {
for (int i = 0; i < 6; i++) {
if (mouseX > boxes[i].x) {
boxes.[i].openIt();
}
}
}
如果我打印i
,我将获得i
System.out.println(i);
如何打印i
的上一个值?我不想使用i-1
,因为我在项目中使用随机数。
答案 0 :(得分:0)
int i= -1;
int prev= -1;
boolean cond = true;
public void mousePressed() {
while(cond){
i=myPositiveRNG.nextInt();//assuming positive numbers, 'cause it's an array index.
if(prev>-1){
System.out.println(prev);
}
if (mouseX > boxes[i].x){
boxes.[i].openIt();
}
prev = i;
cond=isItTimeToGo();
}
根据您的需要量身定制。
答案 1 :(得分:0)
这可能是最直接的方式:
public void mousePressed() {
int lastProcessedI = -1;//Or some reasonable default value
for (int i = 0; i < 6; i++) {
System.out.println("On iteration " + i + " having completed " + lastProcessedI);
if (mouseX > boxes[i].x) {
boxes.[i].openIt();
}
lastProcessedI = i;//mark i as having been processed.
}
}
请注意,应在for循环之前声明lastProcessedI
,否则在循环迭代时它将超出范围。通过在for循环之前声明它,它将保留在mousePressed
方法的包含范围内。
如果您需要保留更多历史记录,这也很容易实现:
public void mousePressed() {
List<Integer> processHistory = new ArrayList<Integer>();
for (int i = 0; i < 6; i++) {
System.out.println("On iteration " + i + " having completed " + processHistory.get(processHistory.size() - 1));
if (mouseX > boxes[i].x) {
boxes.[i].openIt();
}
processHistory.add(i);//store i as having been processed.
}
//here you can get any previously processed i
processHistory.get(processHistory.size() - 2);//I selected 2 arbitrarily, but it will provide the second-to-last i processed.
}