java - 我想不出使用 while 循环将 -1 实现为哨兵值。
问题描述
我不知道使用 while 循环将 -1 实现为哨兵值。请注意,程序需要一直运行,除非用户输入值 -1 它应该停止。从技术上讲,当用户输入标记值(-1)时,程序应该随时停止。
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
while(true) {
randomOne = Math.abs(rand.nextInt()%10);
randomTwo = Math.abs(rand.nextInt()%10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo
+ "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
else {
while (product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
}}
}
}
}
因此,当我们向用户询问输入时,如果他们输入 -1,程序应该停止。
解决方案
您可以在每次迭代时检查该值是否为 -1,然后编写一个 break 语句,但下面是一个稍微干净的实现。
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
boolean playingGame = true;
while (playingGame) {
randomOne = Math.abs(rand.nextInt() % 10);
randomTwo = Math.abs(rand.nextInt() % 10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo + "?");
userInput = scan.nextInt();
while (userInput != -1 && product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
}
if (product == userInput) {
System.out.println("Very Good!");
} else {
playingGame = false;
}
}
scan.close();
}
}
推荐阅读
- java - 如何将环境变量作为命令的一部分传递
- javascript - react-use-gesture useScroll 未检测到滚动事件
- python - Web Scraping 代码中的 JSON 错误,如何修复?
- c# - 迭代思想 JSON 对象并获取特定属性
- c++ - 在 fortran 中运行 Armadilo
- list - OCaml 和 ReasonML 的结果不同
- python - 使用 Python 连接到远程 db2 SQL
- list - 列表分配的值,每次迭代都更改
- android - 数据库颤振与原生(Android)
- pandas - 使用 StandardScaler Python 出错