gpt4 book ai didi

java - If 语句中的不兼容类型

转载 作者:行者123 更新时间:2023-12-01 18:41:34 26 4
gpt4 key购买 nike

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

最佳答案

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

if (answer = input2)

if (answer == input2)

错误的原因是赋值结果仍然是一个 int,而 if 条件需要一个 boolean== 提供了。

关于java - If 语句中的不兼容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com