-1

I've been racking my brain trying to figure out why my if statements won't print, can someone offer some help?

import java.util.Scanner;

public class Sound{
     public static void main(String[] args){

            Scanner x = new Scanner(System.in);

            System.out.println("Enter the type of medium: ");
            String medium = x.nextLine();
            System.out.println("Enter the distance traveled: ");
            double distance = x.nextDouble();


         if(medium == "air"){
            double time = distance/1100;
            System.out.println("This is how long it takes: " + time);
         }
         else if(medium == "water"){
            double time = distance/4900;
            System.out.println("This is how long it takes: " + time);
         }
         else if(medium == "steel"){
            double time = distance/16400;
            System.out.println("This is how long it takes: " + time);
         }
      }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • it might be going in the else part which you didnt code yet – Beingnin Apr 21 '20 at 04:54
  • 1
    use medium.equals("air"). ```if(medium.equals("air"){}``` to compare string... Also, its java, not a javascript. – Biplove Lamichhane Apr 21 '20 at 04:55
  • Java is to Javascript as Pain is to Painting, or Ham is to Hamster. They are completely different. It is highly recommended that aspiring coders try to learn the name of the language they're attempting to write code in. When you post a question, please tag it appropriately - this lets those with knowledge of the language you need help with to see your question. – CertainPerformance Apr 21 '20 at 04:55

1 Answers1

2

String comparisons in Java should be done using equals, e.g. medium.equals("air").

In cases where medium may be null, you can do "air".equals(medium) to avoid a null pointer exception.

The reason why you should use equals is that in the following code:

String a = new String("foo");
String b = new String("foo");

You're creating two different String objects. The == operator checks whether two variables refer to the same object, which means a == b would return false. equals, on the other hand, will compare the actual String contents.

You will commonly use the String a = "foo"; shorthand, which may re-use existing String objects from the JVM's string pool. Because of this, comparing strings with == might work, but it's not something you should rely on, and it won't work with the Scanner.

Erik Lumme
  • 5,202
  • 13
  • 27
  • Down-voted for claiming that *"in the following code: [...] You're creating two different String objects"*, since they are the same `String` object from the *string pool*. – Andreas Apr 21 '20 at 05:10
  • Point taken, I clarified my answer. – Erik Lumme Apr 21 '20 at 06:06