1

我正在为一个任务制作一个程序,我必须让用户猜测一个锁的 3 个数字来解锁它。如果他们不能在 3 内完成,则游戏结束。很简单,据我所知,我做得对,所以不知道我哪里出错了。这是代码部分:

do{
    try{
        String g1Str = JOptionPane.showInputDialog("Enter number 1:");
        g1 = Integer.parseInt(g1Str);
        looper = 2;
    }
    catch(NumberFormatException e){
        JOptionPane.showMessageDialog(null,"Not a Number");
        looper = 1;
    }
    if(g1!=num1){
        JOptionPane.showMessageDialog(null, "Incorrect guess, try again");
        lives = lives - 1;
        looper = 1;
    }
    else if(g1==num1){
        JOptionPane.showMessageDialog(null, "Correct!");
        looper = 2;
    }
}while(looper==1||lives!=0);

这是我的想法:要求用户输入数字,尝试将字符串转换为整数。我使用 try catch 来确保用户确实输入了数字而不是字母。之后,我看看猜测是否等于实数。如果没有,你会失去一个生命(生命之前被声明为 3),然后将 looper 设置为 1,这样你就可以再次尝试猜测你是否有足够的生命。如果它是正确的,则looper被设置为2,并且循环被打破,此时用户可以猜测第二个数字。只要你有足够的生命,我只希望循环保持活动状态,所以我将“while”语句设置为当 looper 为 1 时,或者当生命不等于 0 时。但它似乎不会打破循环如果生命值降为 0。提前致谢

4

3 回答 3

7

您需要更改 while 循环的逻辑:

while (looper == 1 && lives != 0)

现在,如果你有更多的生命,它会继续循环,不管 Looper 是什么。

于 2013-04-02T14:53:53.580 回答
1

您想要布尔值 AND&&而不是 OR ||,如下所示:

while(looper==1 && lives!=0);

||true如果其中一个论点为真,looper1计算结果liveslives同样,如果is not ,您的代码将继续循环0,即使您设置looper2.

&&true仅在两个条件都为真时评估为,如果is not或is则给出false并退出循环。looper1lives0

于 2013-04-02T14:58:52.023 回答
0

替换这个

if(g1!=num1){
      JOptionPane.showMessageDialog(null, "Incorrect guess, try again");
      lives = lives - 1;
      looper = 1;
   }

这样

if(g1!=num1){
   JOptionPane.showMessageDialog(null, "Incorrect guess, try again");
   lives = lives - 1;
   if(lives == 0)
   {
       looper = 2;
   }
   else
   {
       looper = 1;
   }

}

因为当你lives达到 0.looper仍然等于 1 所以循环继续

于 2013-04-02T14:56:31.653 回答