Guess Game
The idea is to make a guessing game:
Pick a number from 1 to 10 (I have three tries) Is it 7? no Is it 8? yes I got it right
or if the computer loses:
Pick a number from 1 to 10 (I have three tries) Is it 7? no Is it 8? no Is it 9? no You win
Here is some starter code:
import java.util.Scanner;
public class Guess
{
public static boolean confirm (Scanner in, String question)
{
System.out.print(question+" ");
String answer= in.nextLine().toUpperCase();
return answer.indexOf("Y") >-1;
}
public static void say(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
say("Pick a number from 1 to 10 (I have three tries)");
int guess = 7;
int tries = 1;
boolean gotIt = confirm(kb,"Is it "+guess+"?");
while (tries<3 && !gotIt )
{
tries++;
guess++;
gotIt = confirm(kb,"Is it "+guess+"?");
}
if(gotIt)
say("I guessed it in "+tries+" tries");
else
say("You won");
}
}
The computer always starts with 7. Maybe it would be better if it was a random number. The Math class has a method called random() that will return a double from 0 to 1 (Including zero, but less than 1). Think of it as a random "percentage" so if we multiply it by 100, it will go from 0 to 99.99999. to drop the decimal we can "type cast" it into an int:
int r = (int)(100*Math.random() );
But now it will return a int from 0 to 99, so if we add one to the result, it will be 1 to 100.
Write a static method called randomInt() that takes two int parameters (arguments) called min and max. The method should will return a random int from min to max. Use this method to make guesses.
