我有以下代码,我正在尝试使用用户在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++;
}
编辑:谢谢你的帮助,我明白了!
答案 0 :(得分: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的documentation。这应该会给你进一步的帮助。 快乐的编码!
答案 1 :(得分:0)
如果在if语句之外声明变量userGuess
,并将其分配到内部,那么您将能够在if语句之外使用它。
另外,正如其他地方所述,你应该将字符串与equals()进行比较,而不是==。
答案 2 :(得分:0)
有两种不错的方式:
更改变量的名称(因此它不会与现有的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++;
}