猜测游戏,(while循环,if语句),再次播放提示不起作用

时间:2017-05-14 02:46:36

标签: if-statement while-loop

所以我是java的新手,我试图通过猜谜游戏应用练习使用while和if语句。

在我被提示再次出场之前,一切似乎都有效。当我输入Y时,循环结束。这不应该发生,因为代码开头的while参数表示如果为true,则keepPlaying。

我试过玩这个参数:while(answer ==“Y”)。我玩过它但它总是不停地退出。请帮忙!!

以下是代码:

import java.util.Scanner;
public class GuessingGame 
{
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        String answer = "Y";
        int guess;
        int number;
        String again;
        boolean keepPlaying = true;


        System.out.println("Let's play a guessing game!");
         while (keepPlaying)
        {
            System.out.println("I'm thinking of a number between 1 and 10.");
            System.out.print("What do you think it is? ");
            guess = sc.nextInt();
            while (guess > 10 || guess < 1)
            {
                System.out.print("I said, between 1 and 10. Try again: ");
                guess = sc.nextInt();
            }
            number = (int)(Math.random() *10 + 1);
            if (guess == number)
            {
                System.out.println("You're right!");

            }
            else
            {
                System.out.println("You're wrong! the number was " + number);

            }
            System.out.print("Play again? (Y or N)");
            answer = sc.next();

            if (answer == "Y")
            {
                keepPlaying = true;
            }
            else
            {
                break;
            }

        }
        System.out.println("Thank you for playing");
    }

}

1 个答案:

答案 0 :(得分:0)

在比较中,您应该使用String要求进行比较:

if (answer.equals("Y"))   // NOTE: I'd use .equalsIgnoreCase(...)
        {
            keepPlaying = true;
        }
        else
        {
            break;
        }

另请注意,由于此比较是在循环结束时,您可以简化为:

keepPlaying = answer.equalsIgnoreCase("Y");

由于您不需要break语句,因为将重新评估循环。