无法获得while循环来停止我的程序?

时间:2015-11-10 15:11:24

标签: java while-loop

好的,所以我试图创建一个游戏是用户有三个猜测猜测序列,RBR,并且我试图使用while循环使程序在变量loopVal超过0时停止(即用户获得正确的序列),但我不能让它工作,任何帮助?提前谢谢。

//猜测代码

  Scanner keyboard = new Scanner(System.in);
  int loopVal = 0;

  while (loopVal < 1){

     System.out.println("Please enter your first guess:");
     String userGuess1 = keyboard.nextLine().toUpperCase();
     if (userGuess1.equals(CORRECT_ANSWER))
     {
        System.out.println("Congratulations you got it on your first try!");
        loopVal++;
     } else
     {
        System.out.println("Sorry that's not right correct, you have 1 guess left");
     }

     //Code for second guess
     System.out.println("Please enter your second guess:");
     String userGuess2 = keyboard.nextLine().toUpperCase();

     if (userGuess2.equals(CORRECT_ANSWER))
     {
        System.out.println("Congratulations you got it on your second try!");
        loopVal++;
     } else
     {
        System.out.println("Sorry that's not right correct, you have 1 guess left");
     }


     //Code for third and final guess
     System.out.println("Please enter your final guess:");
     String userGuess3 = keyboard.nextLine().toUpperCase();

     if (userGuess3.equals(CORRECT_ANSWER))
     {
        System.out.println("Congratulations you got it on your last try!");
        loopVal++;
     } else
     {
        System.out.println("Sorry you didn't get it this time! Play again?");
     }

  }'

3 个答案:

答案 0 :(得分:1)

它没有停止,因为while循环中的检查仅在每次重复时进行一次测试。如果条件在循环中途变得不真实,它将不会退出。最简单的解决方案是添加break以在他们正确猜测时停止。

if (userGuess1.equals(CORRECT_ANSWER))
{
    System.out.println("Congratulations you got it on your first try!");
    loopVal++;
    break;
}

这将立即退出循环,因此它不会要求更多答案。您还应将loopVal增量移至else条件,以便即使您没有得到正确的响应也会退出。

我建议使用类似的东西来修复这些错误(以及删除代码重复):

String[] guesses = {"first", "second", "last"}
while(loopVal < 3){
    System.out.println("Please enter your " + guesses[loopVal] + " guess:");
    String userGuess = keyboard.nextLine().toUpperCase();
    if (userGuess.equals(CORRECT_ANSWER))
    {
        System.out.println("Congratulations you got it on your " + guesses[loopVal] + " try!");
        break;
    } else{
        System.out.println("Sorry that's not right correct, you have " + (2 - loopVal guess left");
        loopVal++;
    }
}

答案 1 :(得分:0)

如果您希望在祝贺到期时退出循环,请使用break代替loopVal++

然后,您可以完全删除loopVal,并使用while(true)

答案 2 :(得分:0)

你正在递增正确的答案,所以不正确的答案永远不会让你用完猜测。

尝试类似:

int loopVal = 0;

while (loopVal < 3){
  System.out.println("Please enter your first guess:");
  String userGuess1 = keyboard.nextLine().toUpperCase();
  if (userGuess.equals(CORRECT_ANSWER)){
    break;
  } else {
    loopVal++;
  }
}