/**
* Guess the computer's random number by typing in a number between 1 and 10.
*
* @author Sameer Saxena
* @version 1.0
*/
import java.util.*;
public class guessingGame {
public static void main(String args[]){
//Start of while loop to allow replaying the game
while (true) {
//Initializing variables
int rnd;
int guessInt;
//Initializing Scanner object
Scanner scan = new Scanner(System.in);
//Initializing Random object for
Random randObject = new Random();
rnd = randObject.nextInt(10) + 1;
System.out.println("This is the one and only guessing game!");
//Starting while loop to allow user 3 guesses
int count = 1;
while (count <= 3) {
//Ask user to enter a guess number, throw an error if a real number was not entered
guessInt = 0;
while (guessInt == 0) {
try {
guessInt = askInput("Enter a number between 1 and 10: ");
} catch (InputMismatchException e) {
System.out.println("You did not enter an actual number.");
}
}
//If the guess was right, print Winner. If the guess was wrong, give the user his/her next chance.
if (guessInt == rnd) {
System.out.println("Winner! Congratulations!");
break;
} else {
System.out.println("Sorry, Wrong. Please try again.");
count += 1;
}//End of if/else statement
} //End of while loop
//Letting the user know what the computer's number was
System.out.println("The computer's number was " + rnd + ".");
//Allowing the user to input whether he/she wants to play again
Scanner scan2 = new Scanner(System.in);
System.out.println("Would you like to play again? Press 1 if so. ");
String answer = scan2.nextLine();
//If the input was not 1, quit the program
if (!answer.equals("1")) {
break;
}//End of if/else statement
} // End of main while loop
} //End of main method
//Function to facilitate asking for input with Scanner class
static int askInput (String text) {
Scanner scan = new Scanner(System.in);
System.out.println(text);
int guess = scan.nextInt();
return guess;
}//End of askInput method
} //End of class
Guess the computer's number between 1 and 10
1 Response
3/10
Write a comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.