简体   繁体   English

做循环不工作? Java的

[英]do while loop not working? Java

I trying to make a do while loop that will keep looping till x either equals y or x equals 7 Here's the code: 我试图做一个while循环,它将保持循环,直到x等于y或x等于7这是代码:

else if(y == 4 || y == 5 || y == 6 || y == 8 || y == 9 || y == 10){
    System.out.println("Value point is: " + y);

    int x = rollDice();
    do{
        System.out.println("Roll again: " + rollDice());
        x = rollDice();
    }
    while(x != y || rollDice() != 7);

    if(x == y){
        System.out.println("You Win!");
    }
    if(x == 7){
        System.out.println("You Lose");
    }
    return;

}}

This is what an output looks like from it: 这是输出的样子:

Dice roll is: 9
Value point is: 9
Roll again: 2
Roll again: 6
Roll again: 6
Roll again: 4
Roll again: 7
Roll again: 11
Roll again: 8
Roll again: 9
Roll again: 2
Roll again: 5
Roll again: 6
Roll again: 8
Roll again: 5
Roll again: 11
Roll again: 5
Roll again: 2
Roll again: 9
Roll again: 6
Roll again: 3
Roll again: 8
Roll again: 8
Roll again: 8
Roll again: 4
Roll again: 7
Roll again: 10
Roll again: 6
Roll again: 5
Roll again: 9
Roll again: 4
Roll again: 7
Roll again: 4
Roll again: 2
Roll again: 8
Roll again: 8
You Win!

Obviously 8 does not equal 9, and since there was a seven near the beginning it should have said "you lose" I just don't where I'm going wrong on this? 显然8不等于9,并且因为在开头附近有7个,所以应该说“你输了”我就不会在这里出错了吗?

EDIT: 编辑:

Please change the loop to this: 请将循环更改为:

do{
    x = rollDice();
    System.out.println("Roll again: " + x);
}
while(x != y && x != 7);

You should only call rollDice() once per iteration. 您应该每次迭代只调用一次rollDice()。 You were calling it 3 times each go-round. 你在每次回合中称它为3次。 Also, the || 另外,|| needed to be changed to &&. 需要更改为&&。

It sounds like where you wrote 这听起来像你写的地方

x != y || rollDice() != 7

you wanted 你自找的

x != y && x != 7

(If you said you wanted to loop until "x either equals y or x equals 7", then you really want &&, not ||, in your condition.) (如果你说你想循环直到“x等于y或x等于7”,那么你真的想要&&,而不是||,在你的条件下。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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