Hello Guys,
I'm having trouble getting my code to run correctly. I need the program to ask the user do they want to continue after they guess the number correctly. If they say "y" the loop should restart if they reply "n" the program should end and close. I will post my code I have so far,any suggestions are appreciated. Thanks in advance.
public static void main(String[] args) {
// Welcome user to program
System.out.println("Welcome to the Random Number Game!\n");
// Create Scanner Object
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// Get Random Double Number
int number_of_tries = 0;
double randNumber = Math.random();
double d = randNumber * 100;
int randomNum = (int)d + 1;
// Beginning Game Message
System.out.println("I'm thinking of a number between 1 - 100.");
System.out.println("Can you guess it?");
// Obtain User Guesses
System.out.println("Let''s Play!\n");
number_of_tries++;
for(int i = 1; i <= 7; i++) {
int userInt = getIntWithinRange(sc, "Enter your guess: ", 1, 100);
if (userInt > randomNum + 10)
System.out.println("Way too high!");
else if (userInt < randomNum - 10)
System.out.println("Way too low!");
else if (userInt > randomNum)
System.out.println("Too high!");
else if (userInt < randomNum)
System.out.println("Too low!");
else
System.out.println("You guessed right!");
// End For Loop
// See if user wants to play again
choice = "x";
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
System.out.println("Attempt number " + number_of_tries );
System.out.println("Do you wish to play again? (y/n): ");
choice = sc.next();
sc.nextLine();
if (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
System.out.println("Error! Not a valid responce!");
} // End if Loop.
} // End While Choice Loop.
} // End While Loop.
} // End Main.
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max) {
int number = 0;
boolean isValid = false;
while (isValid == false) {
number = getInt(sc, prompt);
if (number <= min)
System.out.println("Error! Number must be greater than " + min + ".");
else if (number >= max)
System.out.println("Error! Number must be less than " + max + ".");
else
isValid = true;
}// End While Loop
return number;
} // End Rage Checker
public static int getInt (Scanner sc, String prompt) {
int number = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextInt()) {
number = sc.nextInt();
isValid = true;
} // End If
else {
System.out.println("Error! Invalid integer value. Try again.");
} // End Else
sc.nextLine();
} // End While Loop
return number;
}// End Integer Checker
} // End Class.