while循环用于多重条件

时间:2015-05-27 13:45:29

标签: java while-loop bluej

主要是寻找while循环所在的最后一行,因为我在我的课堂上制作游戏Mastermind,我想保持猜测,而猜测不等于密码。感谢

        if (guess1 == secretcode) {
            System.out.print (" You have guessed one correctly in the right spot!");
        }
        if (guess2 == secretcode1) {
            System.out.print (" You have guessed one correctly in the right spot!");
        }
        if (guess3 == secretcode2) {
            System.out.print (" You have guessed one correctly in the right spot!");
        }
        if (guess4 == secretcode3) {
            System.out.print (" You have guessed one correctly in the right spot!");
        }
         do 
         {
             System.out.println ("Keep guessing you have not won yet!");
             System.out.println ("What is the number one peg in my code???");
        guess1 = Guess.nextInt();
        System.out.println ("What is the number two peg in my code???");
        guess2 = Guess.nextInt();
        System.out.println ("What is the number three peg in my code???");
        guess3 = Guess.nextInt();
        System.out.println ("What is the number four peg in my code???");
        guess4 = Guess.nextInt();
    }
     while  (guess1 != secretcode), (guess2 != secretcode1), (guess3 != secretcode2), (guess4 != secretcode3);

4 个答案:

答案 0 :(得分:2)

使用&&(AND)运算符

代替逗号
do{
    //code to iterate here
}
while ( (guess1 != secretcode) && (guess2 != secretcode1) 
        && (guess3 != secretcode2) && (guess4 != secretcode3) );

记下我添加的额外括号。出于可读性考虑,保留已有的产品是件好事。

正如Jesper在下面评论的那样,您可以对if语句执行相同的操作。清理大量空间。

if ( (guess1 == secretcode) && (guess2 == secretcode1) 
    && (guess3 == secretcode2) && (guess4 == secretcode3) ) {

    System.out.print (" You have guessed one correctly in the right spot!");
}
do {
    //code to iterate here
} while (condition)

答案 1 :(得分:1)

使用AND运算符&&

while  (guess1 != secretcode && guess2 != secretcode1 && guess3 != secretcode2 && guess4 != secretcode3);

答案 2 :(得分:1)

将条件与conditional operators AND(&&),或(||)结合使用:

do {
    ... loop contents ...
} while(guess1 != secretcode &&
        guess2 != secretcode1 &&
        guess3 != secretcode2 &&
        guess4 != secretcode3);

答案 3 :(得分:1)

您应该使用&&运算符,它允许您检查多个条件。 代码:

do {
//loop body
} while(guess1 != secretcode && guess2 != secretcode1 &&  guess3 !=secretcode2 &&  guess4 != secretcode3);

注意:如果你使用&&然后所有条件都需要为循环执行。如果您希望在只有一个条件为真时执行循环,请使用||