If Else Statements with Java using JOptionPane

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21416886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:37:24  来源:igfitidea点击:

If Else Statements with Java using JOptionPane

javaswingif-statementequalsjoptionpane

提问by user3246303

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).

我是编程新手 - 正在学习 Java。我正在尝试使用 JOptionPane 处理 if/else 语句。一切正常,除了语句。我只得到“停下来加油!”的陈述。无论输入什么答案(是或否)。

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);            


     }
}

回答by christopher

if (answer == "yes")

When comparing Stringobjects, you need to use the equalsmethod.

比较String对象时,需要使用该equals方法。

Example

例子

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

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

注意:根据评论的建议,将if语句结构如下更安全:

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

This will not through a NullPointerExceptionis answeris equal to null.

这将不通过NullPointerExceptionanswer等于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 equalsmethod.

在 Java 中,当使用==运算符比较 type 的子类时Object,它会检查这两个对象是否是对同一对象的引用。他们不检查那个对象。因为您正在比较值,所以您需要使用该equals方法。

How it applies to your code

它如何适用于您的代码

Well, let's look at it. You get a Stringtype 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 differentobjects.

好吧,让我们看看它。您StringInputDialog. 所以这是一个String。然后您尝试将其与"yes". 这就是所谓的 a String literal,因此这意味着在那里创建了一个对象,因此是两个不同的对象。

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.

请记住,在对象的情况下,您是在比较引用类型;不是对象值,所以这就是为什么它总是导致false.

回答by But I'm Not A Wrapper Class

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

您必须将字符串与 .equals(...)

if("yes".equals(answer))

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

Using==将比较引用,其中 as.equals(...)比较值。

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 ==.

当您想要比较对象(您创建的类或属于 Java 的一部分,例如String)时,您应该使用.equals(...)(除非您有意比较引用)。当你比较原始数据类型(如intdoublechar,等),你应该使用==

回答by Southpaw Hare

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:

您遇到了有关 Java 中字符串比较的常见问题。将字符串与 '==' 进行比较不会达到您的预期 - 而是使用 String 类中的 '.equals()' :

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:

您通常应该确保您也检查空值,因为对空变量执行 .equals() 会导致崩溃。一般来说,你真的希望你的条件看起来像这样:

if (answer != null && answer.equals("yes"))