Created
December 23, 2013 20:21
-
-
Save wjn/8103960 to your computer and use it in GitHub Desktop.
Guess The Number: a Java version of the first computer game I ever played.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class GuessTheNumber { | |
@SuppressWarnings("unused") | |
public static void main(String[] args) | |
{ | |
final int HIGHEST_NUMBER = 100; | |
final int MAX_GUESSES = 10; | |
int guessCount = 0; | |
String line = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; | |
Scanner in = new Scanner(System.in); | |
int secret = getSecretNumber(HIGHEST_NUMBER); | |
System.out.println("I'm thinking of a secret number between 0 and " + HIGHEST_NUMBER + "."); | |
System.out.println("Can you guess what it is in " + MAX_GUESSES + ((MAX_GUESSES == 1) ? " guess" : " guesses") + " or less?"); | |
int guess = in.nextInt(); | |
while(guessCount < 10) | |
{ | |
guessCount++; | |
int guessesRemaining = MAX_GUESSES - guessCount; | |
switch(evaluateGuess(guess,secret)) | |
{ | |
case "correct": | |
System.out.println("\n" + line); | |
System.out.println(" Wow! I can't believe it! You guessed my secret number in " + guessCount + ((guessCount == 1) ? " guess" : " guesses") + "!"); | |
System.out.println(line + "\n"); | |
playAgain(); | |
break; | |
case "low": | |
System.out.println("\nGood guess, but it's too LOW. Guess again. You have " + guessesRemaining + ((guessesRemaining == 1) ? " guess" : " guesses") + " left."); | |
guess = in.nextInt(); | |
break; | |
case "high": | |
System.out.println("\nNice try, but your guess was too HIGH. Guess again. You have " + guessesRemaining + ((guessesRemaining == 1) ? " guess" : " guesses") + " left."); | |
guess = in.nextInt(); | |
break; | |
} | |
} | |
in.close(); | |
if(guessCount == MAX_GUESSES) | |
{ | |
System.out.println("Uh-oh, You've ran out of guesses."); | |
playAgain(); | |
} | |
in.close(); | |
} | |
public static void playAgain() | |
{ | |
Scanner choice = new Scanner(System.in); | |
// System.out.println("Would you like to play again? [Y/N]"); | |
// if(choice.next().toLowerCase() == "y") | |
// { | |
// main(null); | |
// } | |
// else | |
// { | |
System.out.println("\nThanks for playing!"); | |
System.exit(0); | |
// } | |
// choice.close(); | |
} | |
public static String evaluateGuess(int guess, int secret) | |
{ | |
String result; | |
if(guess == secret) | |
{ | |
result = "correct"; | |
} | |
else if (guess < secret) | |
{ | |
result = "low"; | |
} | |
else | |
{ | |
result = "high"; | |
} | |
return result; | |
} | |
public static int getSecretNumber(int max) | |
{ | |
return (int) (Math.random() * max + 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment