简体   繁体   中英

While loop doesn't change the value of variable

int time=0;
int x=1;
int w=2;
int y=1;
int h=1;
int t=6;
while (x != w && y != h) {
    boolean s = Abc (a,b,c,time);
    if (s == true) {
        time = time+t;
        x++;
    }
    else if (s = false) {
        time = time++;
    }
}

System.out.println(time);

This is a part of program I'm writing for school and my problem is that when the program enters the while loop no matter what I do inside the loop when it exits and prints the variable "time" the value is the same as the value set at the beginning. Am I missing something? (BTW Abc is just a method that should return the value true when I first enter the loop, therefore the value of time should be changed to time+t)

  1. s = false is an assignment, not a comparison. Anyway, you don't need to test if s == false , you just need an else clause (since the original condition checks for s == true ).
  2. There's no reason to assign the result of time++ to time , since it will undo the increment (the post increment operator returns the previous value of the variable, so when you assign that value back to the variable, you cancel the increment).

Change

else if (s = false) {
    time = time++;
}

to

else {
    time++;
}

Edit :

As Anthony Grist commented, even after these fixes, the entire while loop won't be executed at all, since y==h in the beginning.

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