将先前的[random]变量与while Java循环中的当前[random]变量进行比较

将先前的[random]变量与while Java循环中的当前[random]变量进行比较,java,Java,我想记录新的随机整数小于前一个值的次数。我该如何记录这些信息?我想我需要创建一个新的int来存储以前的值,但是我不确定在哪里以及如何插入这个新变量 public static void Ant(Random r) { int fall = 0; int target = 6; int step = r.nextInt(7); while (step != target) { step = r.nextInt(7);

我想记录新的随机整数小于前一个值的次数。我该如何记录这些信息?我想我需要创建一个新的int来存储以前的值,但是我不确定在哪里以及如何插入这个新变量

 public static void Ant(Random r) {
      int fall = 0;
      int target = 6;
      int step = r.nextInt(7);
      while (step != target) {
         step = r.nextInt(7);
         if (**previous step > current step**) {
            fall++;
         }
      }
      System.out.println("number of falls: " + fall);
   }
}

是的,您需要一个新的局部变量。在迭代结束时,将当前
步骤
分配给
上一步
(如下所示)


您需要保留两个
int
变量来保留以前的随机值和当前的随机值。检查以下代码:

public static void Ant(Random r) {
    int fall = 0;
    int target = 6;
    int step1 = r.nextInt(7);
    while (step1 != target) {
        int step2 = r.nextInt(7);
        if (step1 > step2) {
            fall++;
        }
        step1 = step2;
    }
    System.out.println("number of falls: " + fall);
}

如果我把
intpreviousstep=0这会有什么不同吗?或者是有什么原因让我们最好将其声明为一个随机对象呢?在这段代码中,step的第一个值是在while循环之前计算出来的。这就是为什么我使
步骤
等于
上一步
。如果使
previousStep
0,则可以在while循环内开始随机值生成。但是,如果检查可能会产生误导,因为您第一次总是与0进行比较。这是风格问题
public static void Ant(Random r) {
    int fall = 0;
    int target = 6;
    int step1 = r.nextInt(7);
    while (step1 != target) {
        int step2 = r.nextInt(7);
        if (step1 > step2) {
            fall++;
        }
        step1 = step2;
    }
    System.out.println("number of falls: " + fall);
}