Skip to content

Instantly share code, notes, and snippets.

@jjfiv
Last active February 18, 2022 17:22
Show Gist options
  • Save jjfiv/43322f3ebe1b35b283eeb90001577ff0 to your computer and use it in GitHub Desktop.
Save jjfiv/43322f3ebe1b35b283eeb90001577ff0 to your computer and use it in GitHub Desktop.
P2 CS201 GuessingGame starter
import java.util.Random;
import java.util.Scanner;
// We discussed academic honesty, so when you re-type this code, be sure to cite it in a comment!
// This is the only time you MUST cite code from me, the instructor.
public class GuessingGame {
/** One more than the highest possible number in the game. */
private static final int HIGH = 100;
/** The lowest possible number in the game. */
private static final int LOW = 0;
/**
* A Java program will run code in a special ``main`` method.
* Note that Java has two types of comments: block (slash-star ... star-slash),
* and line ("slash-slash") comments.
* For now we ignore args, which is an array of strings that the user might have
* passed in.
*
* @param args command line arguments.
*/
public static void main(String[] args) {
// Create a random number generator:
Random rand = new Random();
// Select a secret number.
final int secretNumber = rand.nextInt(HIGH - LOW) + LOW;
System.out.println("Welcome to the Guessing Game.");
System.out.println("I have selected a number from [" + LOW + "," + HIGH + ").");
// Set the current guess to something that can't be correct.
int guess = LOW - 1;
// We use a Scanner to turn characters from System.in into numbers.
Scanner scanner = new Scanner(System.in);
while (guess != secretNumber) {
System.out.println("What is your guess? ");
if (!scanner.hasNextInt()) {
String whatYouSaid = scanner.nextLine().trim();
System.out.println("Please enter a valid number! You said '" +
whatYouSaid + "' but I don't understand.");
// Continue takes us around the loop again.
continue;
}
guess = scanner.nextInt();
// Give the player a hint!
if (guess > secretNumber) {
System.out.println("Your guess of " + guess + " is too high.");
} else if (guess < secretNumber) {
System.out.println("Your guess of " + guess + " is too low.");
}
}
// The only way we exit the loop is if we have won.
System.out.println("Congratulations, you've won!");
System.out.println("Thanks for playing!");
// Always close resources that you open (We'll talk more about this later).
scanner.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment