I'm having an issue I haven't ran into yet. I wrote a guessing game in java to guess a number between 1 and 1000. The program should loop until the player decides he or she no longer wants to play. I can not get it to loop however. If I take out the Scanner class at the bottom of the program it loops fine but I need the scanner class to complete the program as required in my class. If the user types "no" in the scanner class the while loop variable is set to false and the program terminates just as it should. But I cannot get it to loop if the user chooses "yes" and the while loop variable remains true. After "yes" is typed the program just pauses and nothing happens, and the program doesn't end. Any help would be greatly appreciated.
import javax.swing.*;
import java.util.*;
public class RandomGuess3
{
public static void main(String[] args)
{
String userGuess;
String playAgain;
int guessNum;
int randomNum = (1+(int)(Math.random()*1000));
int guessCount = 0;
boolean correct = false;
boolean startGame = true;
boolean newGame = false;
if(launchGame() == true)
startGame = true;
while(startGame == true)
{
do
{
userGuess = JOptionPane.showInputDialog(null,
"I'm thinking of a number between 1 and 1000."
+"\nEnter your guess:", "Guessing Game",
JOptionPane.QUESTION_MESSAGE);
guessNum = Integer.parseInt(userGuess);
if(guessNum != randomNum)
if(guessNum < randomNum)
JOptionPane.showMessageDialog(null, "Sorry you guessed too low");
else
JOptionPane.showMessageDialog(null, "Sorry you guessed too high");
if(guessNum == randomNum)
correct = true;
++guessCount;
}while(guessNum != randomNum);
if(correct == true)
JOptionPane.showMessageDialog(null, "CONGRATULATIONS!"
+"\nYou guessed correctly!"
+"\nAnd it only took "+guessCount+" tries.");
Scanner input = new Scanner(System.in);
System.out.print("Want to play again? Enter yes or no >> ");
playAgain = input.nextLine().toUpperCase();
if(playAgain.equals("NO"))
startGame = false;
else
startGame = true;
}
}
public static boolean launchGame()
{
int letsPlay;
boolean startGame;
letsPlay = JOptionPane.showConfirmDialog(null,
"Want to play a guessing game?");
startGame = (letsPlay == JOptionPane.YES_OPTION);
System.out.println("startGame is "+startGame);
return startGame;
}
}
Scanner?randomNumremains the same - you should assign a new value before entering the outer loop once again. The same goes forguessCount, it should be reassigned to 0. Moreover, mixing Swing andSystem.inis very confusing.