Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.*; // import everything in util
public class GuessingGame {
public static int min = 0, max = 100; // set min to 0 and max to 100
public static boolean running = true; // set this to false, and next time it loops, it will stop
public static Scanner scanner = null; // this will be initialized by `main`
public static Random rand = new Random(); // this will be used to get a random number later
public static void main(String[] args) {
scanner = new Scanner(System.in); // set it up to read input from the console
while(running) { // repeat until running is set to false
reset(); // reset the game
System.out.println("Player is thinking of a random number between " + min + " and " + max); // print ranges for user
while(true) { // repeat forever (or, until it is breaked by a break statement)
int guess = getRandom(min, max); // get a random number between min and max
System.out.println("\nComputer guesses: " + guess); // print out the computer's guess
System.out.print("Player responds, this is (high, low, correct): "); // make an input prompt for the user
String input = getInput().toUpperCase(); // get input and convert it to upper case
if(input.startsWith("H")) { // the number is higher cause it starts with H
min = guess + 1; // so make this the minimum guess
} else if(input.startsWith("L")) { // the number is lower
max = guess - 1; // so make this the maximum guess
} else if(input.startsWith("C")) { // this guess is correct
break;
} else {
System.out.println("Invalid option, try again.");
}
}
System.out.println("\nComputer says: Good game, Dave."); // print "game over" message
System.out.print("Play again? "); // make an input prompt again
String choice = getInput().toUpperCase(); // get input and make it uppercase again
if(choice.startsWith("Y")) { // the requirements say to check if it starts with Y or N
running = true; // continue playing, the loop resets
System.out.println(); // print empty line
} else {
running = false; // this will end the loop
}
}
System.out.println("Thanks for playing!"); // say "thanks" after the loop has ended
}
// call this function to reset the game
public static void reset() {
min = 0;
max = 100;
}
// returns a string, the input from the console
public static String getInput() {
return scanner.nextLine();
}
// gets a random number between min and max
public static int getRandom(int min, int max) {
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
You can’t perform that action at this time.