java - 如何仅显示输入的相同数字的尝试次数和 1 计数
问题描述
帮助!这是猜谜游戏,我有一个问题,它需要打印尝试次数,但只有一次计数到用户输入的多次连续多次相同的数字。
public static void main(String[] args) {
// TODO code application logic here
int ans,guess;
final int max = 10;
Scanner jai = new Scanner(System.in);
Random no = new Random();
int att = 0;
ans = no.nextInt(max) + 1;
while (true){
System.out.println("Enter a number between 1 to 10");
guess = jai.nextInt();
att += 1;
att;
if (guess == ans){
System.out.println("You are correct, the answer is :"+ ans);
System.out.println(att +" attempts to find the correct number!");
System.exit(0);
}else if (guess > ans){
System.out.println("Too Large");
}else if (guess < ans){
System.out.println("Too Small");
例如:需要数 5 一次 输入 1 到 10 之间的数字 5 太小 输入 1 到 10 之间的数字 5 太小 输入 1 到 10 之间的数字 8 太小 输入 1 到 10 之间的数字 9 太小 输入一个介于 1 到 10 之间的数字 10 你是对的,答案是:10 5 次尝试找到正确的数字!
解决方案
您可以利用 Set 和它的非重复值:https ://docs.oracle.com/javase/7/docs/api/java/util/Set.html 。
也不鼓励使用系统退出,最好使用布尔值来定义何时退出while循环
所以你可以这样尝试:
//...
boolean correct;
Set<Integer> tries = new HashSet();
while (!correct){
System.out.println("Enter a number between 1 to 10");
guess = jai.nextInt();
att ++;
tries.add(guess);
if (guess == ans){
System.out.println("You are correct, the answer is :"+ ans);
System.out.println(att +" attempts to find the correct number!");
System.out.println(tries.size() +" unique tries");
correct = true;
}else if (guess > ans){
System.out.println("Too Large");
}else if (guess < ans){
System.out.println("Too Small");
}
您还可以使用 Set 告诉用户他是否已经尝试过该答案,方法是检查 iftries.contains(guess)
或检查结果,add(...)
因为它返回布尔值
推荐阅读
- http - 什么是单http请求?
- scala - Spark 使用临时 AWS 凭证:java.lang.NoClassDefFoundError: org/apache/hadoop/fs/StorageStatistics
- x11 - 带有 X11 隧道的 SSH 提供身份验证错误
- python - 从字典中删除重复项
- image - 带有 cacheHeight 的 FadeInImage
- google-colaboratory - 有没有办法在 google.colab.kernel.comms 对象上注册消息处理程序回调?
- pandas - 如何过滤 NaN 值的数据框并创建这些 NaN 值的新数据框
- ios - 在 iOS(Flutter)中使用自定义 URL 方案从 BankID 应用程序重定向不起作用
- c# - 遍历字符串以返回数字只是检索第一个数字?
- javascript - 如何在 Windows 上关闭 node.js 实时服务器?