我是Java的新手,我需要帮助。我创建了一个游戏,程序会生成一个随机数(1-100),用户必须猜测它。游戏工作。我的问题是,当用户猜出正确的数字时,我必须使用showConfirmDialog询问播放器,如果他们想再次播放,请使用循环播放或再次播放。谁能告诉我该怎么做?任何事情都将不胜感激。
package guessinggame;
import javax.swing.JOptionPane;
public class Guessinggame {
public static void main(String[] args) {
int guess;
int numguess = 0;
int usernum;
int result = JOptionPane.showConfirmDialog(null, " Do you want to play? ", " Notice ", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
do {
//game starts here
guess = (int) (Math.random() * 100 + 1);
usernum = Integer.parseInt(JOptionPane.showInputDialog("enter your guess"));
numguess++;
if (usernum > guess) {
System.out.println(usernum + " is too high. Try again");
} else if (usernum < guess) {
System.out.println(usernum + " is too low. Try again");
}
} while (guess != usernum);
int IQ = ((int) (Math.random() * 100 + 1)) + numguess;
JOptionPane.showMessageDialog(null, " Correct, it took you " + numguess + " tries. Your IQ is " + IQ);
//Use showConfirmDialog to if player wants to play again.
// If user chooses yes, play game again. If user chooses no end game
} else if (result == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "Quiting? Bye!");
System.exit(0);
}
}
}
答案 0 :(得分:0)
您可以通过如下方式无限循环地将所有内容包装在while循环中:
package guessinggame;
import javax.swing.JOptionPane;
public class Guessinggame {
public static void main(String[] args) {
int guess;
int numguess = 0;
int usernum;
while(true) { //Start of while loop
int result = JOptionPane.showConfirmDialog(null, " Do you want to play? ", " Notice ", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
do {
//game starts here
guess = (int) (Math.random() * 100 + 1);
usernum = Integer.parseInt(JOptionPane.showInputDialog("enter your guess"));
numguess++;
if (usernum > guess) {
System.out.println(usernum + " is too high. Try again");
} else if (usernum < guess) {
System.out.println(usernum + " is too low. Try again");
}
} while (guess != usernum);
int IQ = ((int) (Math.random() * 100 + 1)) + numguess;
JOptionPane.showMessageDialog(null, " Correct, it took you " + numguess + " tries. Your IQ is " + IQ);
//Use showConfirmDialog to if player wants to play again.
// If user chooses yes, play game again. If user chooses no end game
} else if (result == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "Quiting? Bye!");
System.exit(0);
}
} //End of While Loop
}
}