因此,在尝试创建一个随机数生成器以提示用户不断猜测生成的数字直到他们猜对时,我遇到了一些问题。
一切正常,直到我尝试添加再次播放的选项。问题在于,如果他们猜错了数字,它会不断重复相同的错误消息,无论他们猜的太高、太低,还是输入无效,都会不断地重复。如果第一次猜对了号码,则一切正常,并提示再次播放并完美运行。
问题是,我使用了 2 个 for 循环,因为当他们开始猜测时,我不想要:
“这个程序会生成一个从 0 到 100 的随机数,你必须猜。”
每次他们猜错答案时都输出,我只希望在他们选择再次播放选项时输出,这就是我制作嵌套 for 循环的原因。但是问题仍然存在,在显示相同答案的第一个错误猜测之后,内部 for 循环进入无限循环。
import javax.swing.JOptionPane;
import java.util.Random;
import javax.swing.UIManager;
import java.awt.*;
public class RandomNumberGuesser{
public static void main(String[] args){
UIManager m1=new UIManager();
Color g = Color.gray;
Color lg = g.brighter();
m1.put("OptionPane.background", lg);
m1.put("Panel.background", lg);
int x;
for(x = 1; true; x++){
Random random = new Random();
int randomNumber = random.nextInt(100);
System.out.println(randomNumber);
JOptionPane.showMessageDialog(null,
"This program will generate a random number from 0 to 100 which you have to guess.",
"Number Guesser",
JOptionPane.INFORMATION_MESSAGE);
String guess = JOptionPane.showInputDialog(null,
"Guess a number.",
"Guess",
JOptionPane.QUESTION_MESSAGE);
if(guess == null){
System.out.println("The user has terminated the program");
System.exit(0);
}
int guess1 = Integer.parseInt(guess);
int y;
for(y = 1; true; y++){
if(guess1 > 100 || guess1 < 0)
JOptionPane.showMessageDialog(null,
"Guess is out of range!\nPlease enter valid input.",
"Invalid Input",
JOptionPane.WARNING_MESSAGE);
else if(randomNumber > guess1)
JOptionPane.showMessageDialog(null,
"You guessed too low.\nGuess again!",
"Your guess",
JOptionPane.INFORMATION_MESSAGE);
else if(randomNumber < guess1)
JOptionPane.showMessageDialog(null,
"You guessed too high.\nGuess again!",
"Your guess",
JOptionPane.INFORMATION_MESSAGE);
else{
JOptionPane.showMessageDialog(null,
"You guessed the number right!\nIt took you "+y+" attempt(s) to guess it.",
"Congratulations!",
JOptionPane.INFORMATION_MESSAGE);
if (JOptionPane.showConfirmDialog(null, "Want to play again?", "Play again?",
JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
System.out.println("Play again soon!");
System.exit(0);
}
else{
y = 0;
break;
}
}
}
}
}
}