【问题标题】:Problems with String Input [duplicate]字符串输入问题[重复]
【发布时间】:2014-02-05 18:20:06
【问题描述】:

所以,由于某种原因,我在使用字符串输入时遇到了问题。

我不知道为什么。也许这是每个人都知道的非常愚蠢的事情,但我不知道。

这是无效的代码:

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'");
    }
}

是的,实际上我在其他地方确实有一个教程方法,而且效果很好。

主要问题是,如果我输入'Yes'或Yes,它仍然会进入最后的else。

我只放了

String i = input;

并从

if(input == "Yes") {

因为那时它也不起作用。

那我做错了什么?

【问题讨论】:

标签: java eclipse string comparison


【解决方案1】:

不要使用== operator 来比较Strings,而是使用equals(),正如详细解释的herehereherehere 或众多重复项中的任何一个。

if ("Yes".equals(input))

甚至

if ("yes".equalsIgnoreCase(input))

请注意,在 inputnull 并且在其上调用操作 (Yoda condition) 的情况下,对 "yes" 字面量调用操作以避免可能的 NullPointerException

来自Java Language Specification, Chapter 15 - Expressions, section 21 - Equality Operators

15.21.3。引用相等运算符 == 和 !=

虽然 == 可用于比较 String 类型的引用,但这样的相等性测试确定两个操作数是否引用同一个 String 对象。如果操作数是不同的 String 对象,则结果为 false,即使它们包含相同的字符序列(第 3.10.5 节)。可以通过方法调用 s.equals(t) 来测试两个字符串 s 和 t 的内容是否相等。

【讨论】:

    【解决方案2】:

    如前所述,问题在于您使用== 比较器比较此字符串,而不是.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'");
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2020-02-14
    • 2011-05-23
    • 1970-01-01
    相关资源
    最近更新 更多