Skip to content

Instantly share code, notes, and snippets.

@boloutaredoubeni
Created January 14, 2016 15:31
Show Gist options
  • Select an option

  • Save boloutaredoubeni/7b1875d3dd0a22971165 to your computer and use it in GitHub Desktop.

Select an option

Save boloutaredoubeni/7b1875d3dd0a22971165 to your computer and use it in GitHub Desktop.
Guess a random number recursively
package com.boloutaredoubeni.guessinggame;
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final int NUM_OF_GUESSES = 5;
public static void main(String[] args) {
System.out.println("Guess if the chosen number is odd or even");
runGame(NUM_OF_GUESSES, 0);
}
private static boolean checkAnswer(final int correctNum) {
System.out.printf("Guess:\t");
Scanner scanner = new Scanner(System.in);
final String userGuess = scanner.nextLine();
return (userGuess.toUpperCase().equals("EVEN") && ((correctNum % 2) == 0))
|| (userGuess.toUpperCase().equals("ODD") && ((correctNum % 2) == 1));
}
private static void runGame(final int triesLeft, final int timesCorrect) {
System.out.printf("Tries:\t%d\tScore:\t%d\n", triesLeft, timesCorrect);
if (triesLeft <= 0) {
System.out.println("You are out of tries");
if (timesCorrect != 3) {
System.out.println("You Won");
} else {
System.out.println("You lost");
}
promptPlayAgain();
}
if (timesCorrect == 3) {
System.out.println("You won!!");
promptPlayAgain();
return;
}
final Random rand = new Random();
if (checkAnswer(rand.nextInt(2))) {
runGame(triesLeft-1, timesCorrect+1);
} else runGame(triesLeft-1, timesCorrect);
}
private static void promptPlayAgain() {
System.out.println("Would you like to play again?");
Scanner scanner = new Scanner(System.in);
final String userAns = scanner.nextLine();
if (userAns.toUpperCase().equals("YES")) {
runGame(NUM_OF_GUESSES, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment