Last active
September 27, 2022 20:08
-
-
Save spukles/e47539bc34e86d62a1b1e93b8141561c to your computer and use it in GitHub Desktop.
This file contains 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.text.NumberFormat; | |
import java.util.Random; | |
import java.util.Scanner; | |
public class HiLo { | |
public static void main(String[] args) { | |
String repeat = "y"; | |
//loop for playing the game | |
while (repeat.equals("y") || repeat.equals("Y") || repeat.equals("Yes") || repeat.equals("yes")) { | |
//Random Number 0-100 | |
Random r = new Random(); | |
int target = r.nextInt(101); | |
//Number of guesses | |
int n = 1; | |
//User inputs a guess | |
int guess; | |
Scanner scan = new Scanner(System.in); | |
System.out.print("Enter a guess: "); | |
guess = scan.nextInt(); | |
//Loop for guessing | |
while (guess != target) { | |
//when the guess is out of range | |
if (guess > 100 || guess < 0) { | |
System.out.println("That guess is out of range!"); | |
System.out.print("Enter a guess: "); | |
guess = scan.nextInt(); | |
} | |
//Guess is too big | |
else if (guess > target) { | |
n++; | |
System.out.print("Too high. Enter a guess: "); | |
guess = scan.nextInt(); | |
} | |
//Guess is too small | |
else if (guess < target) { | |
n++; | |
System.out.print("Too low. Enter a guess: "); | |
guess = scan.nextInt(); | |
} | |
} | |
// Prints Congratulations as well as the number of guesses guessed | |
System.out.println("Congratulations! It took you " + n + " guesses!"); | |
// Calculates & prints the score | |
NumberFormat f = NumberFormat.getPercentInstance(); | |
f.setMinimumFractionDigits(0); | |
double score = 1.0/n; | |
System.out.println("You scored: " + f.format(score) + "."); | |
// Asks the user if the want to play again | |
System.out.print("Play again? "); | |
// reads user's input on whether they want to play again | |
repeat = scan.next(); | |
} //The while loop ends here | |
// A yes, Yes, y, or Y will allow the user to play again, anything else ends the game | |
System.out.println("Good-bye."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment