I am supposed to be doing a reverse guessing game where the user picks a number and the computer guesses but I am having a hard time getting the computer to not repeat what it has already guessed. But this is what I have done so far:
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;
}
Aucun commentaire:
Enregistrer un commentaire