该代码很好,但是我试图使该代码要求播放器再次播放,这是如果播放器想要再次播放,则该代码将继续运行。但是,这没有发生。
package exercise;
import javax.swing.JOptionPane;
import java.util.Random;
public class guessing_game {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(101);
boolean userCorrect = false;
String userInputString;
int userGuessedNumber;
int count = 0;
String play= "n", UserCorrect="y" ;
do {
count=count+1;
userInputString =JOptionPane.showInputDialog("Guess the number:");
userGuessedNumber =Integer.parseInt( userInputString );
if( userGuessedNumber > randomNumber) {
JOptionPane.showMessageDialog( null, "Too high, try again");
}
else if( userGuessedNumber < randomNumber) {
JOptionPane.showMessageDialog( null, "Too low, try again");
}
else {
JOptionPane.showMessageDialog( null, "Yes, you guessed the number, the guessed number is: " + randomNumber);
JOptionPane.showMessageDialog( null, "The number your guessed is " + count);
userCorrect =true;
play = JOptionPane.showInputDialog("Play again? (y/n) : ");
}
}
while( userCorrect!=true || play == UserCorrect);
}
}
答案 0 :(得分:0)
您正在尝试将两个字符串与==
进行比较。在大多数情况下,它将始终返回false
。
如果要比较两个字符串,请使用.equals(String)
函数。
为您,将play == UserCorrect
更改为play.equals(UserCorrect)
。