2

I am new to to programming - and am learning Java. I am trying to work an if/else statement using JOptionPane. Everything works okay, except the statements. I only get the statement "Stop and get gas!" no matter what the answer entered (yes or no).

Any help would be appreciated!

//This program determine if I have to stop for gas on the way in to work. 

import javax.swing.JOptionPane;
import java.util.*;

public class GasIndicator
{

     public static void main(String[] args)
     {
          String answer;
          String outputStr1;
          String outputStr2;

     answer =            
          JOptionPane.showInputDialog ( "Do you have at least an eighth tank of gas? yes or no " );



          outputStr1 = "You can drive straight to work";
          outputStr2 = "Stop and get gas!";

          if (answer == "yes")

              JOptionPane.showMessageDialog(null, outputStr1, "Gas", JOptionPane.INFORMATION_MESSAGE);


          else 
              JOptionPane.showMessageDialog(null, outputStr2, "Gas", JOptionPane.INFORMATION_MESSAGE);


         System.exit(0);            


     }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user3246303
  • 21
  • 1
  • 1
  • 2
  • @JonSkeet Does a question count as a duplicate even in the case where the OP didn't realize that their problem was related in the first place? – Southpaw Hare Jan 28 '14 at 21:13
  • 2
    @SouthpawHare More definitely. The core problem here has been answered in the duplicate question, so it's definitely worth giving a link to it, where a more comprehensive explanation of the problem can be found. – christopher Jan 28 '14 at 21:14
  • @christopher What I mean is, while certainly it is true that the problem lies in the usage of ==, the "duplicate" question relates to explaining why it is bad to someone who already knew it was a problem and wanted to know why, whereas this question relates to someone who didn't even know that the == vs equals problem existed to begin with and would have had no way to ask the "duplicate" question. Doesn't this make the questions different based on intent? – Southpaw Hare Jan 28 '14 at 21:17
  • @SouthpawHare I would say it is, yes. Closing as duplicate isn't necessarily a moral judgement on the post/poster -- it's just a way of saying that we've answered this question before, which we have. – yshavit Jan 28 '14 at 21:17

3 Answers3

9
if (answer == "yes")

When comparing String objects, you need to use the equals method.

Example

if(answer.equals("yes")) {
    // Do code.
}

NOTE: As advised on the comments, it is safer to structure the if statement as follows:

if("yes".equals(answer)) {
    // Do code.
}

This will not through a NullPointerException is answer is equal to null.

Explanation

In Java, when using the == operator to compare subclasses of type Object, it will check if those two objects are references to the same object. They do not check the value of that object. Because you're comparing value, you need to use the equals method.

How it applies to your code

Well, let's look at it. You get a String type from the response of the InputDialog. So this is one String. You then attempt to compare it with "yes". This is, what's called a String literal, so this means an object is created there two, so two different objects.

Remember in the case of objects, you're comparing the reference types; not the object value, so that's why it always resulted in false.

christopher
  • 26,815
  • 5
  • 55
  • 89
3

You must compare Strings with .equals(...)

if("yes".equals(answer))

Using == will compare references where as .equals(...) compares the values.

When you want to compare Objects (classes you make or that are a part of Java such as String), you should use .equals(...) (unless you intentionally want to compare references). When you compare primitive data types (such as int, double, char, etc.), you should use ==.

1

You are experiencing a common issue regarding String comparisons in Java. Comparing Strings with '==' will not do what you are expecting - instead, use the '.equals()' in the String class:

if (answer.equals("yes"))

You should generally make sure you check for null as well, since performing .equals() on a null variable would cause a crash. In general, you really want your conditional to look like this:

if (answer != null && answer.equals("yes"))
Southpaw Hare
  • 1,535
  • 3
  • 24
  • 50
  • If you use [Yoda conditions](http://en.wikipedia.org/wiki/Yoda_conditions) (placing the constant first, so you have a non-null object reference to compare to) you can usually avoid the null check. Although it may sound a little weird, it has some advantages (see wiki link above for details). – Catalin Pol Jan 28 '14 at 21:24
  • It's true, I know about and agree with this methodology! I just didn't want to bring it up here since it's a fairly deep topic on its own. – Southpaw Hare Jan 28 '14 at 21:25