我有以下一段代码,我稍后尝试使用用户在 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++;
}
编辑:谢谢你的帮助,我想通了!
试试这段代码:
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 关于字符串的文档。这应该会给你进一步的帮助。祝您编码愉快!
有两种不错的方法:
-
更改变量的名称(使其不会与现有的 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++; }
-
只需在每次让用户输入内容时使用相同的 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++; }
如果你在 if 语句外部声明变量userGuess
,并且只在内部分配它,那么你就可以在 if 语句之外使用它。
此外,正如其他地方所述,您应该将字符串与 equals() 进行比较,而不是 ==。