I need some help on being able to add a play again feature. If the user guesses the right value, ask them if they want to play (using Y/N) and reset the random number.
Also, is there any way to modify my code so that the user can first set the parameters of the random number by setting a min. and max. number? Thanks!
Here's what I've got so far:
import java.util.Scanner; import java.util.Random;
class Random_Number_Game {
int maxNumber;
int minNumber;
int numberToBeGuessed = 0;
int totalGuessesTaken = 0;
public Random_Number_Game(int min, int max) {
maxNumber = max;
minNumber = min;
int userGuess;
numberToBeGuessed = createRandomNumber();
do {
totalGuessesTaken++;
userGuess = retrieveUserInput();
} while (!checkUserInput(userGuess));
} // end GuessMyNumber method
public int retrieveUserInput() {
Scanner keyboard = new Scanner(System.in);
String userinput;
do {
System.out.print("Guess a number between 0 and 100: ");
userinput = keyboard.nextLine();
} while (!isUserInputValid(userinput));
return Integer.parseInt(userinput);
} // end retrieveUserInput method
public int createRandomNumber() {
Random r = new Random();
return r.nextInt(101);
}
public boolean checkUserInput(int guess) {
if (guess == numberToBeGuessed) {
System.out.println("Right! It took you " + totalGuessesTaken + " guesses.");
return true;
} else {
if (guess > numberToBeGuessed) {
System.out.println("Too High!");
} else {
System.out.println("Too Low!");
}
}
return false;
}
public static boolean isUserInputValid(String testerString) {
try {
Integer.parseInt(testerString);
} catch (NumberFormatException e) {
System.out.println("That input is invalid. You entered '" + testerString + "'. Please enter a proper integer: ");
return false;
}
return true;
}
public static void main(String args[]) {
new Random_Number_Game(0, 101);
}
}
Aucun commentaire:
Enregistrer un commentaire