首页 > 解决方案 > 如何仅显示输入的相同数字的尝试次数和 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 次尝试找到正确的数字!

标签: javarandomjava.util.scanner

解决方案


您可以利用 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(...)因为它返回布尔值


推荐阅读