0

我在 if 语句中收到类型不兼容的错误消息。变量“answer”和“input2”都是整数,所以我不确定这两者是如何不兼容的。任何帮助或见解将不胜感激!

public static void addingGame()
{

    System.out.print("\n");

    System.out.println("********* Part 2: Adding Numbers **********");

    System.out.print("\n");

    Scanner inputReader = new Scanner(System.in);

    System.out.print("Would you like to add some numbers?(y/n)");
    String input = inputReader.next();

    while (!input.equals("y") && !input.equals("n"))
    {
        System.out.print("I need a y/n: ");
        input = inputReader.next();
    }    

    while (input.equals("y"))
    {
        Random numberGenerator = new Random();
        int randomNumber1 = numberGenerator.nextInt(10);
        int randomNumber2 = numberGenerator.nextInt(10);
        int answer = ((randomNumber1) + (randomNumber2));
        System.out.print( randomNumber1 + " + " + randomNumber2 + " =: ");
        int input2 = inputReader.nextInt();
        if (answer = input2)
        {
            System.out.print("Right! " + answer + " is the answer.");
        }
        else
        {
            System.out.print("Sorry, " + answer + " is the answer.");
        }

        System.out.print("Would you like to play again?(y/n)");
        input = inputReader.next();
        while (!input.equals("y") && !input.equals("n"))
        {
            System.out.print("Sorry - I need a y/n: ");
            input = inputReader.next();
        }
    }    

    System.out.print("\n");

    System.out.print("Thanks - Let's move on to Part 3...");
4

1 回答 1

4

=当您想要比较值 ( ==)时,您正在使用赋值运算符。改变

if (answer = input2)

if (answer == input2)

错误来自这样一个事实,即分配的结果仍然是a ,int其中if条件期望 a boolean,它==提供了。

于 2013-11-05T00:04:22.113 回答