所以,出于某种原因,我只是在使用字符串输入时遇到问题。
我不知道为什么。也许这是每个人都知道的一些令人难以置信的蠢事,但我没有。
这是无法运作的代码:
import javax.swing.*;
public class Thing {
public static void main(String[] args) {
String input;
JOptionPane.showMessageDialog(null,"Welcome to the test...");
input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
String i = input;
if(i == "Yes") {
tutorial();
} else if(input=="'Yes'") {
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
} else {
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
}
是的,我确实在其他地方有一个教程方法,并且它工作正常。
主要问题是,如果我输入“是”或“是”,它仍然会进入最后的其他位置。
我只放入
String i = input;
并从
更改了它if(input == "Yes") {
因为它不起作用。
那我做错了什么?
答案 0 :(得分:4)
请勿使用==
operator来比较String
,而是使用equals()
,完全解释here,here,here ,here或任何重复的任何内容。
if ("Yes".equals(input))
甚至
if ("yes".equalsIgnoreCase(input))
请注意,在"yes"
文字上调用了该操作,以避免在NullPointerException
为input
的情况下可能null
并且在其上调用了操作({{ 3}})。
<强> 15.21.3。参考等式运算符==和!=
虽然==可用于比较String类型的引用,但这样的相等性测试确定两个操作数是否引用相同的String对象。如果操作数是不同的String对象,则结果为false,即使它们包含相同的字符序列(第3.10.5节)。可以通过方法调用s.equals(t)测试两个字符串s和t的内容是否相等。
答案 1 :(得分:1)
如上所述,问题是您使用==
比较器而不是.equals()
方法比较此字符串。
如果您正在运行 Java 7 ,我的建议是,为了更清洁的解决方案,我也建议将其包含在switch
语句中:
JOptionPane.showMessageDialog(null,"Welcome to the test...");
String input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
switch (input) {
case "Yes":
tutorial();
break;
case "'Yes'":
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
break;
default:
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}