【问题标题】:How do I get my simple guessing game to work?如何让我的简单猜谜游戏发挥作用?
【发布时间】:2013-11-10 21:19:15
【问题描述】:

这是我学习 Java 的第二天,我创建了一个简单的猜谜游戏,您必须在其中尝试猜测“魔法单词”,但是每次运行它时,当我输入正确的单词时,它总是会出现“错了!”。

任何帮助将不胜感激。

package textpac;
import javax.swing.JOptionPane;
public class textclass {

public static void main(String[] args) {
    String inputText = JOptionPane.showInputDialog("What is the magic word?");
    String outputText = null;
    if (inputText == "themagicword"){
        outputText = "Well done!";
    } 
    if (inputText != "themagicword"){
        outputText = "Wrong!";
    }
    JOptionPane.showMessageDialog(null, outputText);
}
}

【问题讨论】:

    标签: java string swing


    【解决方案1】:

    比较字符串时,使用.equals(...) 方法而不是== 运算符:

    if (inputText.equals("subscribe")){
        outputText = "Well done!";
    } 
    if (!(inputText.equals("themagicword"))){
        outputText = "Wrong!";
    }
    

    问题是== 比较一个String 变量的引用或object 是否与另一个String 变量的引用完全相同,这不是你想知道的。相反,您想知道两个 String 对象是否以相同的顺序、相同的大小写共享相同的字母,为此,如果大小写不重要,请使用.equals(...) 方法或.equalsIgnoreCase(...)

    【讨论】:

    • 附加信息 字符串是 Java 中的对象。所以当你比较字符串时,你检查对象是否相等。所以如果你想比较字符串的值,最好使用 String.equals() 方法。
    • "Text".equalsIgnoreCase(variable) 将防止出现空指针异常的可能性 ;)
    • 您可以使用else 而不是进行两次比较。
    • 谢谢大家的帮助,很高兴我也能帮忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多