简体   繁体   English

如何使我的简单猜谜游戏正常工作?

[英]How do I get my simple guessing game to work?

It's my second day of learning Java and I have created a simple guessing game, where you have to try and guess the 'magic word', however every time I run it, when I type the correct word it always comes up with 'Wrong!'. 这是我学习Java的第二天,我创建了一个简单的猜谜游戏,您必须尝试猜测“魔术字”,但是,每次我运行它时,当我键入正确的单词时,总会出现“错! '。

Any help would be greatly appreciated. 任何帮助将不胜感激。

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

When comparing Strings, use the .equals(...) method instead of the == operator: 比较字符串时,请使用.equals(...)方法而不是==运算符:

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

The problem is that == compares if a String variable's reference or object is the exact same as that of another String variable's, and that is not what you want to know. 问题是==比较一个String变量的引用或对象是否与另一个String变量的引用或对象完全相同,而这不是您想知道的。 Instead you want to know if the two String objects share the same letters, in the same order, with the same capitalization, and for that, use the .equals(...) method or .equalsIgnoreCase(...) if capitalization isn't important. 相反,您想知道两个String对象是否以相同的顺序以相同的顺序共享相同的字母,并且使用相同的大小写,为此,如果没有使用大写,请使用.equals(...)方法或.equalsIgnoreCase(...)不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM