-1

我试图在 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,因为我在我的项目中使用随机数。

4

2 回答 2

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

根据您的需要定制。

于 2013-11-05T22:53:41.207 回答
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.
  }
}

请注意,lastProcessedI应该在您的 for 循环之前声明,否则循环迭代时它将超出范围。通过在 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.
}
于 2013-11-05T23:00:27.903 回答