【问题标题】:Why is this always evaluating as false? [duplicate]为什么这总是评估为假? [复制]
【发布时间】:2015-05-11 00:05:59
【问题描述】:

这是一个简单的程序,它生成 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);
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    问题在于您使用的是Integer 包装类而不是int 原语,但您使用的是标识(==)而不是对象相等性(equals)来进行比较。将您所有的Integers 更改为ints。

    请注意,对于小整数,这实际上会起作用,因为优化了缓存 Integer 对象的小值,但这仍然是一个错误。

    【讨论】:

    • 啊,非常感谢 :)
    【解决方案2】:

    sum.equals(answer) 可能会给你想要的结果。

    【讨论】:

      【解决方案3】:

      您遇到的问题是因为您将一个对象与另一个对象进行比较,以查看它们是否是同一个对象,而事实并非如此。

      尝试使用intValue() 方法或equals 方法比较原始值。

      if (sum.intValue () == answer.intValue ()) 
      {
        ....
      }
      

       if (sum.equals (answer))
      

      【讨论】:

        【解决方案4】:

        == 是参考比较,而 .equals() 是值比较

        .equals() 可以被认为是“有意义的等价”,而 == 通常意味着“字面上的等价”

        试试 if (sum.equals(answer))

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-14
          • 2019-03-25
          • 2018-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-20
          相关资源
          最近更新 更多