试图使用else if语句?

时间:2016-12-06 15:26:27

标签: java

我的代码是一个猜谜游戏:用户可以选择5,10或20次尝试,并且有多次猜测计算机的randomNumber选择。如果他们的猜测是错误的,那么我的代码会猜测并打印出如果他们的猜测高于或低于randomNumber,并且如果他们的猜测是正确的,则打印出祝贺消息。 我需要有一条消息说:“抱歉,(用户名称),你没猜到神奇数字,(randomNumber),(他们选择多少猜测)尝试。” 这只是在他们使用了所有的猜测之后,仍然没有猜到这个数字。 我写了我的代码我得到一个错误,说我有一个没有If的其他,但我觉得这可能不是我唯一的问题。有人能告诉我如何将其包含在我的代码中吗? 这是:

2 个答案:

答案 0 :(得分:0)

这对你有帮助。

 for(int i = 1; i <= numberOfGuesses; i++){
   System.out.print("Enter guess #"+i+": ");
   guess = scan.nextInt();
        if (guess > randomNumber)
                    System.out.println("Your guess, "+guess+", is greater than the magic number.");
        else if (guess < randomNumber)
                    System.out.println("Your guess, "+guess+" is less than the magic number.");
        else if (guess == randomNumber){
                    System.out.println("Congratulations, "+name+"! You guessed the magic number in "+i+" guesses.");
                    break;
                }
        if (i == numberOfGuesses)
             System.out.println("Sorry, "+ name+"you did not guess the magic number,"+ randomNumber+"in"+numberOfGuesses+ "tries.");

    }

输出:

Please enter your name: user
Would you like to try to guess a number? (Yes or No):yes
How many guesses would you like? (5, 10, 20)5
Enter guess #1: 1
Your guess, 1 is less than the magic number.
Enter guess #2: 100
Your guess, 100, is greater than the magic number.
Enter guess #3: 2
Your guess, 2 is less than the magic number.
Enter guess #4: 3
Your guess, 3 is less than the magic number.
Enter guess #5: 4
Your guess, 4 is less than the magic number.
Sorry, useryou did not guess the magic number,71in5tries.

答案 1 :(得分:0)

错误在于:

break;

使用中断时, if 语句会被取消。这就是你得到这个错误的原因。

想一想:

之后,您将 if 语句与多个 else if 放在一起。

当您说中断时,您的程序会假定您已完成所有语句并希望启动新内容。

在您的代码中,“新内容”是其他 - 这显然不起作用,因为没有 if 语句可以逻辑访问。< / p>

长话短说 - 当使用 if else if 时,您实际上不需要使用 break 。在大多数情况下,卷曲括号绰绰有余。

我希望能帮助你。如果你还有任何疑问,请打我。

相关问题