反向猜谜游戏(java)

时间:2016-12-08 22:33:50

标签: java random

我本来应该做一个反向猜谜游戏,用户选择一个数字而计算机猜测但我很难让计算机不再重复它已经猜到的内容。但这是我到目前为止所做的:

public static void main(String[] args)
{ 
    Scanner console = new Scanner(System.in);
    intro();
    game (console);

}

/*
 * This method just prints out the intro before the game.
 */

public static void intro ()
{
    System.out.println("This program has you, the user, choose a number");
    System.out.println("between 1 and 10, then I, the computer, will try");
    System.out.println("my best to guess it.");
    System.out.println();
}
 /*
  * This method is the game part that is going to ask the user to choose a number (1-10)
  */
public static boolean  game (Scanner console)
{
    String user;
    int min= 1;
    int max = 10;
    int computer;
    int numberOfGuesses = 0;
    boolean again = false; 
    Random rand = new Random();
    System.out.println("User, what is your number? ");
    int usernumber = console.nextInt();

    while (!again)
    {
        if (min==max)
        {
            computer= min;
        }
        else
        {
            computer = Math.abs (rand.nextInt()) % (max - min) + min;
        }

        System.out.print("Is it " + computer + "? (y/n) ");
         user = console.next();


        if (user.charAt(0) == 'y')
        {
            numberOfGuesses++;
            System.out.println("I go your number of " + usernumber + " correct in " + numberOfGuesses + " guess(es).");
            again = true;
            return again;
        }

        if (user.charAt(0) == 'n')
        {


            if(min >=computer)
            {
                min = computer +1; 
            }
            else
            {
                max = computer -1 ;
            }
            numberOfGuesses++;
            again = false;
        }

    }


    return again;
}

3 个答案:

答案 0 :(得分:0)

您好,欢迎来到Stack Overflow!

考虑尝试使用布尔数组,每次猜到一个数字时,将数组[value-1]的值更改为true。然后,当计算机在打印到屏幕之前猜测时,检查该值是否在数组中。如果它不是很棒的话,我再也不会猜到了:)

答案 1 :(得分:0)

您可以使用'设置'来存储已生成的数字,并通过简单地将其添加到Set来检查该数字是否已存在,例如:

Set<Double> generated = new HashSet<>();

while(!again)
{

if (min==max)
{
    computer= min;
}
else
{
    computer = Math.abs (rand.nextInt()) % (max - min) + min;
}

if(!generated.add(computer)){
    continue;
}
如果元素已存在,则add的{​​{1}}方法返回Set。通过这种方式,您可以检查该号码是否已生成。

Herefalse方法的Javadoc。

答案 2 :(得分:0)

以下是最简单的代码:

boolean hasValue[] = new boolean[10];
    while(true) {
        System.out.print("User, what is your number: ");
        int usernumber = sc.nextInt();
        int guess = rnd.nextInt(10) + 1;
        hasValue[guess] = true;
        if(usernumber != guess && !hasValue[usernumber])
            System.out.println("Oops!");
        else {              
            System.out.println("Bingo!");
            break;
        }
    }