Hi everybody!
I am brand new to Java and this is my first post here. This is my code for my attempt at a number guessing program. It runs the way I intended except for the part where it asks the user if they would like to continue.
I had intended for an answer of 'yes' to make the program play another game and have any other response terminate the program. This worked early on as I was building the program but as soon as I used Scanner for input of the users guess I ran into trouble.
Now when I run the program it plays the game fine once and asks the continue question but does not wait for a response from the user, and just terminates.
I am thinking the problem lies with my use of Scanner instance myScanner, Line 43. Can I not use this same instance of myScanner to get input for both the int guess and the continue game String?
import java.util.Scanner; public class NumberGuess { static Scanner myScanner = new Scanner(System.in); public static void main(String args[]) { String userPlayAgainQuestion; int userGuess = 0; System.out.println("Welcome to Number Guess!\n"); do { int secretNumber = ((int)(Math.floor(Math.random() * 10))) + 1; // Generate random number between 1-10 while((userGuess < 1) || (userGuess > 10)) // Loop until userGuess is valid int { System.out.print("Please enter your guess: "); userGuess = myScanner.nextInt(); if((userGuess < 1) || (userGuess > 10)) // Check that userGuess is valid int { System.out.println("Guess must be between 1-10. Please try again."); continue; } if(userGuess == secretNumber) { System.out.println("You guessed it!! The number was " + userGuess + "!!"); } else { System.out.println("Sorry the secret number was " + secretNumber + "."); } } System.out.print("Do you want to play again? Type \'yes\' to continue: "); userPlayAgainQuestion = myScanner.nextLine(); // Problem here?????? <- Line 43 }while(userPlayAgainQuestion.equalsIgnoreCase("yes")); System.out.println("\n\nThanks for playing! See you soon."); } }