简体   繁体   中英

Why does it print out 0?

Why is the answer 0 and not 1? I know it has something to do with the boolean sentence, but I can't figure out how it works. From my understanding, the while loop stops when i and j are both equal to 1.

public void random(){
    int i = 0;
    int j = 2;
    int k = 0;
    boolean keepGoing;
    keepGoing = i<j;
    while (keepGoing && k<2) {
        i++;
        j--;
        k++;
    }
    System.out.println(j);
}

prints out 0

You are probably saying that because you think the keepGoing variable will stop the loop... Well the keepGoing variable won't change at all! You instantiated your variable with this:

boolean keepGoing;
keepGoing = i<j;

This expression will look at the values of i and j at that moment in the code , replace these variables with their values (respectively 0 and 2 at that moment), and just process the comparison. As i is less than j at that moment in the code it will return true and set keepGoing to true. After that, keepGoing won't change itself each time i or j changes. That is not how it works. The value of keepGoing will only change if you set another value in it! In general, a variable will only change if there is an explicit line (or method) encountered that tells it to change. So if in your case you want keepGoing to change each time you change i or j , you'll have to explicitely recalculate keepGoing each time that happens. In your case this will be at the end of your while block:

    while (keepGoing && k<2) {
        i++;
        j--;
        k++;
        keepGoing = i<j;  //explicitely recalculate value of keepGoing
    }

It's because you are decreasing the integer j and increasing the integer k.

The while steps look like:

  1. i = 0, j = 2, k = 0
  2. i = 1, j = 1, k = 1
  3. i = 2, j = 0, k = 2

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