If语句中的不兼容类型

时间:2013-11-05 00:03:32

标签: java

我在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...");

1 个答案:

答案 0 :(得分:3)

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

if (answer = input2)

if (answer == input2)

错误来自于分配结果仍为int这一事实,其中if条件需要boolean==提供。{ / p>