-1

I am comparing 2 double values which I receive from user input.
Here is the code:

import java.util.Scanner;

class Main {
public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter two numbers: ");
  Double a = scan.nextDouble();
  Double b = scan.nextDouble();
  if (a>b){
   System.out.println("Largest is: " + a);}
  if(b>a){
   System.out.println("Largest is: " + b);}
   System.out.println(a+""+b);
  if (a==b){
    System.out.println("Largest is: " + b);}
  }
}

This code works when I input double values that are greater than/ less than each other. However, this code does not work when I input two of the exact same double values(for example: 9.0 and 9.0)
Why is this?
Thanks in advance

joshkmartinez
  • 654
  • 1
  • 12
  • 35

1 Answers1

-2

Like @GBlodgett and @ScaryWombat said in the comments, a Double is an object, so in my code, I basically compare if the objects are the same.
So to compare the 2 double values I can do:
a.equals(b) or use .compare() function like this: Double.compare(a,b)==0
However, I wouldn't need to do this at all if I just use double instead of Double

joshkmartinez
  • 654
  • 1
  • 12
  • 35