java - 循环和 showConfirmDialog
问题描述
我是 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);
}
}
}
解决方案
您可以通过将所有内容无限地包装在 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
}
}
推荐阅读
- python - pyaudio 录音 python
- node.js - Sequelize:如何将 findAll 结果作为 Model.create 值传递
- regex - Solr 如何支持用于分面搜索的 REGEX 条目?
- android - 如果 String 的最后一个字符包含这个数组 Kotlin
- redis - Redis,XREADGROUP 流与块一年,愚蠢?
- javascript - 转到新页面时运行脚本
- arrays - 尽管定义了数组大小,但 C 中的预期常量表达式
- mongodb - 选择一个数组的一个数组匹配一个条件的文档
- node.js - Node.JS AES 解密截断初始结果
- reactjs - 使用 getServerSideProps 保护路由