55 lines
2.1 KiB
Java
55 lines
2.1 KiB
Java
import java.util.Random;
|
|
import java.util.Scanner;
|
|
|
|
/*
|
|
CS6 Challenge Solution
|
|
|
|
Original Challenge Description: Write a program that generates
|
|
a random number, and repeatedly asks the user to guess the number,
|
|
telling them if they're too low, too high, of if they guess correctly.
|
|
The program should end once they guess the correct number.
|
|
*/
|
|
public class Main {
|
|
public static void main(String[] args) {
|
|
//Setup our random number generator and a scanner
|
|
//to get input from the user
|
|
Random random = new Random();
|
|
Scanner scan = new Scanner(System.in);
|
|
|
|
//Generate a random integer 0-100 (inclusive)
|
|
int randomValue = random.nextInt(101);
|
|
|
|
//Create a value for guess and set it to something that
|
|
//definitely isn't going to be the random number we just
|
|
//generated. We do this because the while loop that we are
|
|
//going to use needs to run so long as the guess does not
|
|
//equal the random value we generated. If it's something
|
|
//we know isn't possible for the random number, then
|
|
//we know our loop will run properly at least once.
|
|
int guess = -1;
|
|
|
|
//While the user hasn't guessed the right number
|
|
while(randomValue != guess) {
|
|
//Ask the user for a number, and overwrite
|
|
//the value of guess with that number
|
|
System.out.print("Guess the number: ");
|
|
guess = scan.nextInt();
|
|
|
|
//This if statement just checks to see if the user's guess
|
|
//is less, more or the same as what the random generated
|
|
//number was. If the guess is the same as the random number
|
|
//the condition of the while loop will handle getting out
|
|
//of the loop, so no need to call break.
|
|
if(guess < randomValue) {
|
|
System.out.println("You're too low");
|
|
} else if(guess > randomValue) {
|
|
System.out.println("You're too high");
|
|
} else {
|
|
System.out.println("You guessed the right number");
|
|
}
|
|
}
|
|
|
|
//Close our scanner, for good measure
|
|
scan.close();
|
|
}
|
|
} |