![](/img/trans.png)
[英]Java guess game. How do I use data validation to check if a number is within a certain range?
[英]Java - Guess a number game. User has 6 attempts. I've gotten so far as when the 6th attempt is input the game just shuts down
我无法让程序从这里循环到开始,也无法创建会话以将每次尝试写入高分文本文件并保存尝试次数和用户的最佳尝试。
我希望程序弹出另一个JOptionPane
框,说用户已经使用了他们所有的尝试,并询问他们是否想再次播放,以便它循环回到开始。 我还必须创建一个会话,用户在开始时输入他们的名字,并且该会话中的每次尝试都被写入一个高分文本文件并保存。
下面是我到目前为止得到的编码。
import javax.swing.JOptionPane;
import java.util.Random;
public class RandomNumberGuesser{
public static void main(String[] args) {
Random random = new Random();
int attempts = 0; // Number of attempts
int randomNumber = random.nextInt(100);
System.out.println(randomNumber);
// This outside the loop so is showed just ONE time
JOptionPane.showInputDialog(null,
"This program will generate a random number from 0 to 100 which you have to guess.\nNumber Guesser \nPlease enter your name."
,JOptionPane.QUESTION_MESSAGE);
while (true && attempts < 6) {
attempts++;
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);
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 "
+ attempts + " 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 {
randomNumber = random.nextInt(100);
System.out.println(randomNumber);
attempts = 0;
}
}
}
}
}
根据程序,很明显,在第 6 次尝试后,循环退出并且程序结束。 如何打开一个无限循环,即 while(true) 然后在 while 循环中将此作为您的第一次检查
while(true){
if(attempts >= 6){
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 {
randomNumber = random.nextInt(100);
System.out.println(randomNumber);
attempts = 0;
}
}
}
....Rest of your code goes here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.