跟踪前面的for in for循环java

时间:2013-11-05 22:47:57

标签: java for-loop

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

2 个答案:

答案 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.
}