反向猜测游戏(java)
我应该做一个反向猜测游戏,用户选择一个数字,计算机猜测,但我很难让计算机不重复它已经猜到的。但这是我迄今为止所做的:反向猜测游戏(java),java,random,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 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;
}
大家好,欢迎来到Stack Overflow
考虑尝试使用布尔数组,每次猜测一个数字时,将数组[value-1]处的值更改为true。然后,当计算机在打印到屏幕之前猜测时,检查该值是否在数组中。如果不是很好,我不会再猜了:)你可以使用“Set”来存储已经生成的数字,并检查数字是否已经存在,只需将其添加到
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;
}
Set generated=newhashset();
而(!再次)
{
如果(最小值==最大值)
{
计算机=分钟;
}
其他的
{
computer=Math.abs(rand.nextInt())%(max-min)+min;
}
如果(!generated.add(计算机)){
持续
}
add
method ofSet
如果元素已经存在,则返回false
。通过这种方式,您可以检查该数字是否已经生成
是添加方法的Javadoc。下面是最简单的代码:
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;
}
}