java - 再试一次 Do-While 循环
问题描述
这是一个非常简单的程序。计算机和用户在 0-3 之间选择一个数字。如果用户没有猜到与计算机相同的数字,我希望程序循环回来。
String input; // input is a string variable
int cpucrazy;
int convertstring;
// 第一步 //
input = JOptionPane.showInputDialog("Guess a number between 0-3");
convertstring = Integer.parseInt(input);
// 随机部分 //
Random ran = new Random ();
cpucrazy = ran.nextInt(3);
// 计算!
if (cpucrazy < convertstring) {
JOptionPane.showInputDialog(null, "Your guess is too high. Guess again?"); }
else if (cpucrazy > convertstring) {
JOptionPane.showInputDialog(null, "Your guess is too low. Guess again?"); }
else JOptionPane.showMessageDialog(null, "Correct!!");
解决方案
if (cpucrazy < convertstring) {
JOptionPane.showInputDialog(null, "Your guess is too high. Guess again?"); }
else if (cpucrazy > convertstring) {
JOptionPane.showInputDialog(null, "Your guess is too low. Guess again?"); }
else JOptionPane.showMessageDialog(null, "Correct!!");
您需要在上面的代码周围放置一个 while 循环(或某种类型的循环构造)并退出构造 when:cpucrazy == convertstring
或留在循环构造中 whilecpucrazy != convertstring
循环可能类似于以下伪代码:
b = random();
do
{
input a;
if( a != b )
{
if(a < b )
{
print "Too low";
}
else
{
print "Too high";
}
}
} while( a != b );
print "You got it correct"
推荐阅读
- java - 访问 Java admin SDK Firestore 实例的关闭选项
- python - 有没有办法在 POST 方法的主体中发送函数
- python - 如何在不更改 Python 中的原始列表变量的情况下修改列表?
- python-3.x - 在一列中填写不同类别的NA值
- flutter - Flutter Multiple DropdownButton 使用 List 创建
- ios - yarn ios, BUILD FAILED , iOS Simulator 部署目标, Skipping duplicate build file, & Capabilities for Signing & Capabilities 可能不起作用
- javascript - 下拉菜单不显示 onClick React.js
- c++ - 我们如何一起编译和运行多个 .h 和 .cpp 以及一个 main.cpp 文件
- sql - SQL 触发器 AFTER INSERT 未遵循我的 IF 语句并且未删除新行
- reactjs - 为什么 HashRouter 和 BrowserRouter 不能一起工作?