Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created November 6, 2012 11:32
Show Gist options
  • Save DominicFinn/4024153 to your computer and use it in GitHub Desktop.
Save DominicFinn/4024153 to your computer and use it in GitHub Desktop.
Number guessing
package guessinggame;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("********************************");
System.out.println("Guessing game");
System.out.println("1. Enter a max number");
System.out.println("2. Think of a number between 0 and your max");
System.out.println("3. I'll try and guess it.");
System.out.println(" type h for higher");
System.out.println(" type l for lower");
System.out.println(" type y for if I am right");
System.out.println(" type q for to quit");
System.out.println("********************************");
// 1. The computer asks the user for a maximum value (max), which the user inputs.
System.out.println("pick a number maximum number?");
int max = scan.nextInt();
int min = 0;
//the start time of guessing
long startTime = System.nanoTime();
//used to determine if the guess was right or not
boolean correctGuess = false;
boolean outOfNumbers = false;
//used to help the computer know where to guess next or to quit
char feedback = '\0';
while(correctGuess == false && feedback != 'q' && outOfNumbers == false) {
int guess = randomGuess(min, max);
System.out.println("Is your number " + guess + "?");
feedback = scan.next().toCharArray()[0];
switch(feedback) {
case 'h':
min = guess;
break;
case 'l':
max = guess;
break;
case 'y':
correctGuess = true;
break;
case 'q':
break;
}
if((min +1) == max) {
outOfNumbers = true;
}
}
if(correctGuess) {
long stopTime = System.nanoTime();
System.out.println("Excellent it took me " + (stopTime - startTime) + " miliseconds to guess!");
} else {
if(outOfNumbers) {
System.out.println("I'm out of numbers! Play fair.");
} else {
System.out.println("Too bad, try again some time");
}
}
}
private static int randomGuess(int min, int max) {
Random rand = new Random();
return rand.nextInt(max - min + 1) + min;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment