Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* @author
- * October 5, 2012
- * High-Low Game part 2
- * Description: Part 1 of the High-low Game. Generates a random integer
- * from 0 to 500 that the user guesses. Outputs "higher" or "lower" until
- * number is guessed correctly.*/
- import java.util.*;
- public class Expressions{
- public static void main(String[] args){
- Scanner scan_in = new Scanner(System.in);
- int rndNum = 0, guess = 0, numGuesses = 0;
- int ruledOutNumLow = 0, ruledOutNumHigh = 500;
- int rounds = 0, totalGuesses = 0;
- double averageGuessAmount = 0.0;
- String answer = ""; char response;
- boolean validAnswer = false;
- do{
- numGuesses = 0;
- ruledOutNumLow = 0; ruledOutNumHigh = 500;
- rndNum = (int) (Math.random() * 500);
- do{
- System.out.print("Guess a number between 0 and 500, -1 to give up: ");
- guess = scan_in.nextInt();
- if(guess == -1) break;
- if(guess != rndNum){
- if(guess < rndNum){
- if(guess < ruledOutNumLow){
- printThis(ruledOutNumLow, ruledOutNumHigh);}
- else{
- ruledOutNumLow = guess + 1;
- System.out.println("Your guess is too low.");}}
- else{
- if(guess > ruledOutNumHigh){
- printThis(ruledOutNumLow, ruledOutNumHigh);}
- else{
- ruledOutNumHigh = guess - 1;
- System.out.println("Your guess is too high.");}}}
- numGuesses++;}while(guess != rndNum);
- if(guess != -1){
- System.out.println("Congrats! You guessed the number in " + numGuesses + " tries!");
- rounds++;
- totalGuesses += numGuesses;}
- do{
- System.out.print("Play again? (Y/N): ");
- answer = scan_in.next();
- response = answer.charAt(0);
- if(response == 'Y' || response == 'y' || response == 'N' || response == 'n')validAnswer = true;
- if(!validAnswer)System.out.println("Please enter Y or N.");}while(!validAnswer);}while(response == 'Y' || response == 'y');
- averageGuessAmount = (double)totalGuesses/rounds;
- System.out.println("Thanks for playing!");
- System.out.println("You took an average of " + averageGuessAmount + " guesses per round.");}
- public static void printThis(int low, int high){System.out.println("That number has already been ruled out by prior guesses. Only the numbers " + low + " through " + high + " are valid guesses.");}}
Advertisement
Add Comment
Please, Sign In to add comment