开发者

Java: do while wont while

开发者 https://www.devze.com 2023-03-08 05:16 出处:网络
Anfallare.armees = 10; Forsvarare.armees = 10; do{ Anfallare.slaTarningar(); Forsvarare.slaTarningar(); Anfallare.visaTarningar();
    Anfallare.armees = 10;
    Forsvarare.armees = 10;
 do{
    Anfallare.slaTarningar();
    Forsvarare.slaTarningar();

    Anfallare.visaTarningar();
    Forsvarare.visaTarningar();

    MotVarandra(Anfallare, Forsvarare);

    status(Anfallare, Forsva开发者_StackOverflow社区rare);

    }while(Anfallare.armees == 0 || Forsvarare.armees == 0);

is what I have, I tried also a

 System.out.println(Anfallare.armees + " :: " + Forsvarare.armees);

after this do while and it is 9 and 10, neither of them are 0.

Why does it run this once?


Because, as you point out, after the first run, Anfallare.armees is 9, which does not equal 0, and Forsvarare.armees is 10, which is not equal to 0.

Perhaps you meant

while(Anfallare.armees != 0 && Forsvarare.armees != 0)


while(Anfallare.armees == 0 || Forsvarare.armees == 0)

Means continue only if Anfallare.armees == 0 || Forsvarare.armees == 0. In your example, neither is 0 so it will not loop.

while(Anfallare.armees != 0 && Forsvarare.armees != 0)

Means, stop looping if either are zero (Anfallare.armees != 0 && Forsvarare.armees != 0)

You may actually be wanting:

while (Anfallare.armees != 0 || Forsvarare.armees != 0)

means, stop looping if both are 0


You need to do

while(Anfallare.armees != 0 || Forsvarare.armees != 0);

To make it loop until both of those variables are 0


Because you start as do{}, which forces to execute at least once the code, and then you have while x==0, which is not true. Since it is not true, the loop ends.

As you see in the other answers, you may need to check for x != 0 (not equal to), or even better x>0 (in the event x could take a negative number)

Take some time to read the Oracle's Java tutorials I linked in the other answer to you. It explains the loop logic very well.


If I understand you correctly, your do-while loop body is executed once, but you think it shouldn't have run at all - is this correct?

The reason is, in do-while the loop condition is checked only after the loop body is executed. I.e. it will always run at least once.


It's hard to tell without the complete code, but it may be that you just need to invert the condition:

}while(!(Anfallare.armees == 0 || Forsvarare.armees == 0));


You condition says ... as long as one of them is 0. What you'll want is this:

while(Anfallare.armees > 0 || Forsvarare.armees > 0);


the reason is simple

while loops when the expression is true.

so what you want is

while(Anfallare.armees != 0 || Forsvarare.armees != 0);

but even better I would suggest

while(Anfallare.armees > 0 || Forsvarare.armees > 0);

this would allow you to be sure that your armee count never gets negative ^^

Jason

0

精彩评论

暂无评论...
验证码 换一张
取 消