这是一个简单的程序,可以生成0到1000之间的两个随机数,然后用户输入两个数字的总和。 if语句总是评估为不正确,即使您输入正确的答案和总和并回答匹配。
import java.util.Random;
import java.util.Scanner;
public class mathquiz
{
public static void main(String[] args)
{
Integer num1;
Integer num2;
Integer sum;
Integer answer;
Scanner input = new Scanner(System.in);
Random rand = new Random();
num1 = rand.nextInt(1000); //random number between 0 and 1000
rand = new Random();
num2 = rand.nextInt(1000); //random number between 0 and 1000
System.out.println(" "+num1);
System.out.println("+ "+num2);
sum = num1 + num2; //adding the two random numbers together
answer = input.nextInt();
System.out.println(sum); //test print to see what sum is
System.out.println(answer); //test print to see what answer is
if (sum == answer) //always evaluates as incorrect, I would like to know why
System.out.println("Congratulations! You are correct!");
else
System.out.println("You were incorrect. The correct answer is: "+sum);
}
}
答案 0 :(得分:1)
问题是您使用的是Integer
包装器类而不是int
原语,但您使用的是身份(==
)而不是对象相等(equals
)进行比较。将您的所有Integer
更改为int
。
请注意,对于小整数,这实际上会起作用,因为优化会将Integer
个对象缓存为小值,但它仍然是一个错误。
答案 1 :(得分:0)
sum.equals(answer)
可能会为您提供所需的结果。
答案 2 :(得分:0)
您遇到的问题是因为您正在将一个对象与另一个对象进行比较,以查看它们是否是同一个对象,而不是它们。
尝试使用intValue()
方法比较原始值或使用equals
方法。
if (sum.intValue () == answer.intValue ())
{
....
}
或
if (sum.equals (answer))
答案 3 :(得分:0)
==是参考的比较,而.equals()是值的比较
.equals()可以被认为是"有意义的等同"而==通常意味着"字面意思相同"
尝试 if(sum.equals(answer))