Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package my_guess;
- import java.util.Scanner;
- // Number guessing game . computer picks random number between 0 and max number
- // user keeps guessing number and game tells if high or low or correct
- // when correct it tells how many guesses it took
- // then asks if player wishes to play again
- public class Guess {
- private static int rand, guess, count, MAX;
- private static String play_again = null;
- private static Scanner scan;
- public static void main(String[] args) {
- scan = new Scanner(System.in);
- MAX = 1000;
- intro_game();
- }
- private static void intro_game() {
- System.out
- .println("This is a number guessing game. Try to guess the number I am thinking of");
- System.out.println("from 1 to 1000 in the least amount of tries.");
- System.out.println("I will tell you if it's higher or lower.");
- get_random_number();
- }
- private static void get_random_number() {
- rand = (int) ((Math.random() * (MAX - 1) + 1));
- System.out.println("Now guess the number I am thinking of.");
- guess_check();
- }
- private static void guess_check() {
- while (true) {
- try {
- // get input and also check if it's an Integer
- guess = Integer.parseInt(scan.next());
- break;
- } catch (NumberFormatException ignore) {
- System.out.println("It has to be an integer.");
- count++;// even wrong type of guess is counted
- }
- }
- high_low();
- }
- private static void high_low() {
- count++;
- if (guess > rand) {
- System.out.println("To high.");
- guess_check();
- } else if (guess < rand) {
- System.out.println("To low");
- guess_check();
- } else
- System.out.println("Correct, it took you " + count + " tries");
- play_again();
- }
- private static void play_again() {
- System.out.println("Would you like to play again? (y or n)");
- while (true) {
- try {// keep asking until it's a 'y' or 'n' input regardless of case
- play_again = scan.next();
- if (play_again.equalsIgnoreCase("y")) {
- //reset all
- rand = 0;
- guess = 0;
- count = 0;
- scan.reset();
- break;
- } else if (play_again.equalsIgnoreCase("n")) {
- System.out.println("Thanks for playing.");
- System.exit(0);
- }
- } catch (Exception e) {
- System.out.println("This should never show");
- }
- }
- intro_game(); // restart
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment