简体   繁体   中英

Compare previous [random] variable to a current [random] variable inside a while loop Java

I want to keep track of the number of times that the new random integer is smaller than the previous value. How do I keep track of this? I think I need to create a new int in order to store the previous value but I am not sure where and how to insert this new variable.

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

Yes, you need a new local variable. At the end of an iteration, assign the current step to previousStep (shown below)

int fall = 0;
int target = 6;
int previousStep = r.nextInt(7);  //new local variable
int step = previousStep;
while (step != target) {
   step = r.nextInt(7);
   if (previousStep > step) {
      fall++;
   }
  previousStep = step; //assign current step to previousStep
}

You need to keep two int variables to keep previous random value and current random value. Check below code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM