java - 如何在while循环中重复if语句
问题描述
我试图让用户猜测随机数生成器选择的数字,但我的代码决定,如果它不等于,则坚持一个 if 语句。
System.out.println("Enter a guess between 1 and 200: ");
String guess = input.nextLine();
int userInput = Integer.parseInt(guess);
Random rnd = new Random(seed);
int x = rnd.nextInt(200) + 1;
int currentInt = 1;
String msg = "That was impossible!";
我的 while 循环包含许多 if 语句:
boolean boo = false;
while (!boo) {
if (userInput == x) {
System.out.println("Congratulations! Your guess was correct!");
System.out.println("");
System.out.println("I had chosen " + x + " as the target number.");
System.out.println("You guessed it in " + currentInt + " tries.");
if (currentInt == 1) {
//do something
} else if (currentInt >= 2) {
//do something
} else if (currentInt >= 4) {
...
} else if (currentInt >= 11) {
msg = "Maybe you should play something else";
System.out.println(msg);
}
break;
} else if (userInput > x) {
System.out.println("Your guess was too high - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String highGuess = input.nextLine();
int tooHigh = Integer.parseInt(highGuess);
continue;
} else if (userInput < x) {
System.out.println("Your guess was too low - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String lowGuess = input.nextLine();
int tooLow = Integer.parseInt(lowGuess);
continue;
}
currentInt = currentInt + 1;
}
我的代码运行良好,如果第一次尝试的答案是正确的,那么第一个 if 语句有效,但如果它大于或小于 x,则运行相同的块(如果更大,即使下一个输入小于,也会保持更大)
解决方案
userInput
用tooHigh
和更新tooLow
。
推荐阅读
- java - 即时更改 Spring Data Cassandra 配置
- javascript - 字典中的 Nonce 简写导致资源管理器上的 script1003 错误
- sql-server - 哈希匹配,消耗大部分时间,如何避免呢?
- javascript - 看不见的recaptcha - 挑战没有出现
- c++ - 系统语言环境和非 unicode 程序
- opengl - 如何实现点和阳光OpenGL
- java - 少于 100% 的分支覆盖单元测试。如何解决?
- android - 横幅广告加载失败,在 admob android 上测试广告 ID
- docker - 在主机上进行文件更改时,Docker 容器不会更新
- amazon-web-services - 我可以看到类别,但产品没有显示 Magento2