我试图从下面的图像中获得测试3的预期结果。有人能以正确的方式指出我能够解决它吗?
import java.util.Scanner;
/**
* Write a description of class TwoNumbers here.
* @version 1.0
*/
public class TwoNumbers
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter two numbers (like this: 41.7 -22.5): ");
Double number1 = input.nextDouble();
Double number2 = input.nextDouble();
if(number1 == number2)
{
System.out.println("The first number is equal to the second");
}
else if(number1 > number2)
{
System.out.println("The First number is greater than second");
}
else
{
if(number1 < number2)
System.out.println("The first number is less than second");
}
}
}
答案 0 :(得分:5)
您将double
自动装箱到java.lang.Double
s,这将是相同的,但可能不会使用完全相同的参考。
您应该使用原始double
s:
double number1 = input.nextDouble();
double number2 = input.nextDouble();
或者,如果您使用java.lang.Double
,请使用equals
方法对其进行比较:,
if (number1.equals(number2))
{
System.out.println("The first number is equal to the second");
}
答案 1 :(得分:1)
如果你想比较两个非原始对象是否相等,你应该使用.equals()
而不是==
if(number1.equals(number2)){
System.out.println("The first number is equal to the second");
}