Grant Grant - 2 months ago 6
Java Question

Program is not exiting loop even thought it appears it knows to

I am making a guessing game where the user inputs the top number and the computer selects a number between 1 and the number that the user input. After the correct number is guessed, it is supposed to leave the do-while it is in and move on to the toString, but does not.

Here is an example:

Guessing Game - How many numbers? 10
Enter a number between 1 and 10: 1
Try again.

Enter a number between 1 and 10: 2
Try again.

Enter a number between 1 and 10: 3
Try again.

Enter a number between 1 and 10: 4
Enter a number between 1 and 10:


You can see that it doesn't say "Try again," but yet asked for another guess.

Here is my program

import java.util.Scanner;
import static java.lang.System.*;

public class GuessingGame
{
public int upperBound;
int guesscount = 0;

public GuessingGame(int stop)
{
upperBound = stop;
}

public int playGame()
{
boolean guesscorrectly = false;
Scanner kb = new Scanner(System.in);
int correctNum = (int) ((Math.random()*upperBound) +1);
do{
System.out.print("Enter a number between 1 and " + upperBound + ": ");
int guess = kb.nextInt();
if(guess==correctNum){
guesscount++;
guesscorrectly = true;
}
else{
guesscount++;
System.out.println("Try again.\n");
}
}while(guesscorrectly!=true);
return correctNum;
}

public String toString()
{
return "You correctly guessed " + playGame() + "! It took you " + guesscount + " guesses.";
}
}


And then here is the main

import java.util.Scanner;
import static java.lang.System.*;

public class GuessRunner
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Guessing Game - How many numbers? ");
int upperBound = kb.nextInt();
GuessingGame test = new GuessingGame(upperBound);
test.playGame();
System.out.println(test);
}
}

Answer

Your calling playGame() in your toString() method. You shouldn't do that or it will start the game over...