Learning Java: Guess The Number
I’ve just finished reading the section on Basic I/O on the Java essential classes trail. So I put together a little Guess-The-Number game.
import java.io.*; import java.lang.Math.*; public class NumberGame { private Console c; private int upperBound; private int lowerBound; public NumberGame() { c = System.console(); if (c == null) { System.err.println("Unable to aquire console. Exiting..."); System.exit(1); } } private void playGame() { c.format("Welcome to the guess-the-number game!%n"); c.format("Think of a number between 1 and 100 and I'll try to " + "guess it!%n"); upperBound = 100; lowerBound = 1; boolean finished; do { finished = makeGuess(); } while (finished == false); c.format("Thank you for playing!%n"); } private boolean makeGuess() { if (upperBound == lowerBound) { makeAccusation(upperBound); return true; } else { int choice = ((upperBound - lowerBound) / 2) + lowerBound; if (Math.random() < 0.5) { boolean answer = askYesOrNo(String.format("%nIs your " + "number higher than %d? ", choice)); if (answer) { lowerBound = choice + 1; } else { upperBound = choice; } } else { boolean answer = askYesOrNo(String.format("%nIs your " + "number lower than %d? ", choice)); if (answer) { upperBound = choice; } else { lowerBound = choice - 1; } } } return false; } private boolean askYesOrNo(String query) { int answer = -1; String result; char resultChar = ' '; while (true) { result = c.readLine(query); if (result != "") { result = result.toLowerCase(); if (result.length() > 0) { resultChar = result.charAt(0); if (resultChar == 'y') { return true; } else if (resultChar == 'n') { return false; } } c.format("Please answer 'yes' or 'no'.%n"); } } } private void makeAccusation(int accusation) { boolean result = askYesOrNo(String.format("%nIs your number %d? ", accusation)); if (result) { c.format("Awesome!%n"); } else { c.format("One of us is obviously confused.%n"); } } public static void main(String[] args) { NumberGame ng = new NumberGame(); ng.playGame(); } }