0

我有以下代码,稍后我将尝试使用用户在 if/else 语句中输入的输入:

String userGuess = JOptionPane.showInputDialog("The first card is " 
    + firstCard + ". Will the next card be higher, lower or equal?");

如何在此代码所在的 if/else 语句之外使用他们输入的单词,即“更高”、“更低”或“相等”?我需要他们回答的代码是:

if (userGuess == "higher" && nextCard > firstCard)
{
    String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " 
               + nextCard + ". Will the next card be higher, lower or equal?");
    correctGuesses++;
}

编辑:谢谢你的帮助,我想通了!

4

3 回答 3

1

试试这个代码:

if (userGuess.equalsIgnoreCase("higher") && nextCard > firstCard)
{
    String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " 
           + nextCard + ". Will the next card be higher, lower or equal?");
    correctGuesses++;
}

else if (userGuess.equalsIgnoreCase("higher") && nextCard == firstCard)
{
    String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " 
               + nextCard + ". Will the next card be higher, lower or equal?");
    correctGuesses++;
}

else if (userGuess.equalsIgnoreCase("lower") && nextCard < firstCard)
{
    String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " 
               + nextCard + ". Will the next card be higher, lower or equal?");
    correctGuesses++;
}

String不是原始类型。您不能==改用:

if (userGuess.equalsIgnoreCase("higher") && nextCard > firstCard)
{

查看 Oracle关于字符串的文档。这应该会给你进一步的帮助。快乐编码!

于 2013-11-06T20:15:45.737 回答
0

如果您userGuess在 if 语句之外声明变量,并在内部分配它,那么您将能够在 if 语句之外使用它。

此外,正如其他地方所述,您应该将字符串与 equals() 进行比较,而不是 ==。

于 2013-11-06T20:14:05.230 回答
0

有两种不错的方法:

  1. 更改变量的名称(因此它不会与现有的 userGuess 变量冲突)并在 if 语句之外声明它。

    String nextGuess = "";
    if (userGuess.equals("higher") && nextCard > firstCard) {
        nextGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " + nextCard + ". Will the next card be higher, lower or equal?");
        correctGuesses++;
    }
    
  2. 每次让用户输入内容时,只需使用相同的 userGuess 变量。

    if (userGuess.equals("higher") && nextCard > firstCard) {
        userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " + nextCard + ". Will the next card be higher, lower or equal?");
        correctGuesses++;
    }
    
于 2013-11-06T20:19:02.487 回答