Hi all,

I had posted my code and updated it a few times in another thread and didn't get any response and since I have gotten some things figured out and had posted my long code a few times in the other thread, I thought I would put my last couple questions in a new thread. So anyway, this program generates a random number and the user tries to guess it. After the very first guess, the background should turn red with a message saying that you're getting warmer and any other time you're getting warmer or colder (blue background for colder). Well, it usually turns red after the first guess but sometimes it turns blue after the first guess and I can't figure out how to make sure it turns red after the first guess every time.

The other thing I want to change is, after the user enters a guess, I want the the JTextField to clear itself so that for the next guess, the user doesn't have to backspace to enter a new guess. I feel like I have tried everything but I know I must be missing something. Can anyone give me some advice here on how to fix these two things? Here's my code:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;

public class GuessNumber extends JFrame
{
	private int Guesses = 0;
	private int GuessOld = 0;
	private int number; // application's number
	private JTextField guessInputJTextField; // user input field
	private JLabel prompt1JLabel; // first line of instruction
	private JLabel prompt2JLabel; // second line of instructions
	private JLabel messageJLabel; // displays message of game status
	private JLabel message2JLabel; //display number of guesses
	private JLabel message3JLabel;
	private JLabel random1 = new JLabel("");
	private JButton newGameJButton; // creates new game
	private Color background; // background color of application

 	// set up GUI and initialize values

	public GuessNumber()
	{
		super("Guessing Game");
		setLayout(new FlowLayout());
		background = Color.LIGHT_GRAY; // set background to light gray
		prompt1JLabel = new JLabel("I have a number between 1 and 1000."); // describe game
		add(prompt1JLabel);
		prompt2JLabel = new JLabel("Can you guess my number? Type your Guess and then press 'Enter':"); // prompt user
		add(prompt2JLabel);
		guessInputJTextField = new JTextField(5); // to enter guesses
		guessInputJTextField.addActionListener(new GuessHandler());
		add(guessInputJTextField);
		messageJLabel = new JLabel("");
		add(messageJLabel);
		message2JLabel = new JLabel ("");
		add (message2JLabel);
		message3JLabel = new JLabel ("");
		add (message3JLabel);
		newGameJButton = new JButton("New Game"); // create "New Game" button
		add(newGameJButton); // add newGame button to JFrame

 		Random generator = new Random();
		number = generator.nextInt(1001);//create random number

 		newGameJButton.addActionListener(new ActionListener() // anonymous inner class
   	{
   		public void actionPerformed(ActionEvent e)
   		{
   			theGame ();
   		} // end method actionPerformed
   
      } // end anonymous inner class
   
      ); // end call to addActionListener

 		theGame(); // start new game
	} // end GuessGameFrame constructor

 // choose a new random number
   public void theGame()
   {
   	guessInputJTextField.setText("");
      Random generator = new Random();
      number = generator.nextInt(1001);
      random1.setText("" + number);
      SwingUtilities.updateComponentTreeUI(random1);
      messageJLabel.setText("");
      guessInputJTextField.setEditable(true);
		message2JLabel.setText("");
      Guesses = 0;
      message3JLabel.setText("Enter guess # " + Integer.toString(++Guesses));
		getContentPane().setBackground(Color.LIGHT_GRAY);
	} // end method theGame
 
	// change background color
	class GuessHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			int Guess;
			Guess = Integer.parseInt(guessInputJTextField.getText());
			SwingUtilities.updateComponentTreeUI(guessInputJTextField);
	
			if (Math.abs(number - Guess) < Math.abs(number - GuessOld))
			{
				// Hotter
				getContentPane().setBackground(Color.RED);
				message2JLabel.setText("You're getting warmer!");
				SwingUtilities.updateComponentTreeUI(message2JLabel);
			}

			if (Math.abs(number - Guess) > Math.abs(number - GuessOld))
			{
				// Colder
				message2JLabel.setText("You're getting colder!");
				SwingUtilities.updateComponentTreeUI(message2JLabel);
				getContentPane().setBackground(Color.BLUE);
			}

 			GuessOld = Guess;
			if (Guess > number)
			{
				messageJLabel.setText(+ Guess + " is too high.");
				SwingUtilities.updateComponentTreeUI(messageJLabel);
			}

			if (Guess < number)
			{
				messageJLabel.setText(+ Guess + " is too low.");
				SwingUtilities.updateComponentTreeUI(messageJLabel);
			}// end if

			Guesses++;
			message3JLabel.setText("Enter guess #  " + Integer.toString(Guesses)); 

			if (Guess == number) 
			{
				messageJLabel.setText("Congratulations!  You guessed my number!");
				getContentPane().setBackground(Color.YELLOW);
				message2JLabel.setText("");

				SwingUtilities.updateComponentTreeUI(messageJLabel);
				Guesses++;

				message3JLabel.setText("# of guesses = " + Integer.toString(Guesses));
				SwingUtilities.updateComponentTreeUI(message3JLabel);
				guessInputJTextField.setEditable(false);
			}
		}
	}
}
import javax.swing.JFrame;
   
public class GameGuessNumber
{
	public static void main(String args[]) throws Exception
	{
   	GuessNumber game = new GuessNumber();
   	game.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   	game.setSize(550, 150);
   	game.setVisible(true);
   }
}

The changes you need to make are in the "theGame()" method. They are only two and are marked with the red in the code below.

The first problem you mention (the first guess being colder) was created by the GuessOld variable not being reinitialized every time the game got started again.

The second problem/request (clearing the text field after every guess) is a matter of repeating the clearing occuring every time a new game is created (the first line of the "theGame" method) every time a new guess has been made.

Hope your game rocks!:)

// choose a new random number
   public void theGame()
   {
      guessInputJTextField.setText("");
      Random generator = new Random();
      number = generator.nextInt(1001);
      random1.setText("" + number);
      SwingUtilities.updateComponentTreeUI(random1);
      messageJLabel.setText("");
      guessInputJTextField.setEditable(true);
		message2JLabel.setText("");
      Guesses = 0;
      [B]GuessOld = 0;[/B]
      message3JLabel.setText("Enter guess # " + Integer.toString(++Guesses));
		getContentPane().setBackground(Color.LIGHT_GRAY);
	} // end method theGame

	// change background color
	class GuessHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			int Guess;
			Guess = Integer.parseInt(guessInputJTextField.getText());
			SwingUtilities.updateComponentTreeUI(guessInputJTextField);

			if (Math.abs(number - Guess) < Math.abs(number - GuessOld))
			{
				// Hotter
				getContentPane().setBackground(Color.RED);
				message2JLabel.setText("You're getting warmer!");
				SwingUtilities.updateComponentTreeUI(message2JLabel);
			}

			if (Math.abs(number - Guess) > Math.abs(number - GuessOld))
			{
				// Colder
				message2JLabel.setText("You're getting colder!");
				SwingUtilities.updateComponentTreeUI(message2JLabel);
				getContentPane().setBackground(Color.BLUE);
			}

 			GuessOld = Guess;
			if (Guess > number)
			{
				messageJLabel.setText(+ Guess + " is too high.");
				SwingUtilities.updateComponentTreeUI(messageJLabel);
			}

			if (Guess < number)
			{
				messageJLabel.setText(+ Guess + " is too low.");
				SwingUtilities.updateComponentTreeUI(messageJLabel);
			}// end if

			Guesses++;
			message3JLabel.setText("Enter guess #  " + Integer.toString(Guesses));

			if (Guess == number)
			{
				messageJLabel.setText("Congratulations!  You guessed my number!");
				getContentPane().setBackground(Color.YELLOW);
				message2JLabel.setText("");

				SwingUtilities.updateComponentTreeUI(messageJLabel);
				Guesses++;

				message3JLabel.setText("# of guesses = " + Integer.toString(Guesses));
				SwingUtilities.updateComponentTreeUI(message3JLabel);
				guessInputJTextField.setEditable(false);
			}
                        
                        [B]guessInputJTextField.setText("");[/B]
		}
	}

The changes you need to make are in the "theGame()" method. They are only two and are marked with the red in the code below.

The first problem you mention (the first guess being colder) was created by the GuessOld variable not being reinitialized every time the game got started again.

The second problem/request (clearing the text field after every guess) is a matter of repeating the clearing occuring every time a new game is created (the first line of the "theGame" method) every time a new guess has been made.

Hope your game rocks!:)

// choose a new random number
   public void theGame()
   {
      guessInputJTextField.setText("");
      Random generator = new Random();
      number = generator.nextInt(1001);
      random1.setText("" + number);
      SwingUtilities.updateComponentTreeUI(random1);
      messageJLabel.setText("");
      guessInputJTextField.setEditable(true);
		message2JLabel.setText("");
      Guesses = 0;
      [B]GuessOld = 0;[/B]
      message3JLabel.setText("Enter guess # " + Integer.toString(++Guesses));
		getContentPane().setBackground(Color.LIGHT_GRAY);
	} // end method theGame

	// change background color
	class GuessHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			int Guess;
			Guess = Integer.parseInt(guessInputJTextField.getText());
			SwingUtilities.updateComponentTreeUI(guessInputJTextField);

			if (Math.abs(number - Guess) < Math.abs(number - GuessOld))
			{
				// Hotter
				getContentPane().setBackground(Color.RED);
				message2JLabel.setText("You're getting warmer!");
				SwingUtilities.updateComponentTreeUI(message2JLabel);
			}

			if (Math.abs(number - Guess) > Math.abs(number - GuessOld))
			{
				// Colder
				message2JLabel.setText("You're getting colder!");
				SwingUtilities.updateComponentTreeUI(message2JLabel);
				getContentPane().setBackground(Color.BLUE);
			}

 			GuessOld = Guess;
			if (Guess > number)
			{
				messageJLabel.setText(+ Guess + " is too high.");
				SwingUtilities.updateComponentTreeUI(messageJLabel);
			}

			if (Guess < number)
			{
				messageJLabel.setText(+ Guess + " is too low.");
				SwingUtilities.updateComponentTreeUI(messageJLabel);
			}// end if

			Guesses++;
			message3JLabel.setText("Enter guess #  " + Integer.toString(Guesses));

			if (Guess == number)
			{
				messageJLabel.setText("Congratulations!  You guessed my number!");
				getContentPane().setBackground(Color.YELLOW);
				message2JLabel.setText("");

				SwingUtilities.updateComponentTreeUI(messageJLabel);
				Guesses++;

				message3JLabel.setText("# of guesses = " + Integer.toString(Guesses));
				SwingUtilities.updateComponentTreeUI(message3JLabel);
				guessInputJTextField.setEditable(false);
			}
                        
                        [B]guessInputJTextField.setText("");[/B]
		}
	}

Thank you so much!!! It works great now! I appreciate it so much. I don't know about this simple number guessing game I made but YOU ROCK!:) Thanks again!!!!

I had marked this thread as solved but after running my program many more times, I realized it's still not doing what I need. Sometimes it STILL turns the background blue after the first guess but the response to THAT guess HAS to change the background red. I made the above changes and the JTextField clears each time but, like I said, the program still changes the color to blue sometimes for the first guess when it should ALWAYS be red for that one. I've tried moving things all around with no luck so now I've put it back the way it was. (It looks like the last code that was posted in this thread above.) Can someone please help...again?

Hello BobbieJean,

The problem of the background color can be solved with many ways. I chose to add an "if" statement, highlighted with bold, black letters in the code below.
(Note: There is an explanation at the end of the thread that I believe holds true for that problem and will enable you to solve it however you see fit).

A second problem should me solved for the solution provided to work. The problem is that if the user guesses the number the very first time then, the program reports that the number of guesses is 3. The changes to solve this problem are highlighted with bold, red letters.
(Note: The "else" statement is essentially what happens when the user is wrong. The above are just one solution I came up with. The important thing is that the number of guesses increases once during every try.)

// change background color
    class GuessHandler implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            int Guess;
            Guess = Integer.parseInt(guessInputJTextField.getText());
            SwingUtilities.updateComponentTreeUI(guessInputJTextField);

            if [B]([/B] (Math.abs(number - Guess) < Math.abs(number - GuessOld)) [B]||
                    (Guesses == 1) )[/B] {
                // Hotter
                getContentPane().setBackground(Color.RED);
                message2JLabel.setText("You're getting warmer!");
                SwingUtilities.updateComponentTreeUI(message2JLabel);
            } [B]else[/B] if (Math.abs(number - Guess) > Math.abs(number - GuessOld)) {
                // Colder
                message2JLabel.setText("You're getting colder!");
                SwingUtilities.updateComponentTreeUI(message2JLabel);
                getContentPane().setBackground(Color.BLUE);
            }

            GuessOld = Guess;
            if (Guess > number) {
                messageJLabel.setText(+Guess + " is too high.");
                SwingUtilities.updateComponentTreeUI(messageJLabel);
            }

            if (Guess < number) {
                messageJLabel.setText(+Guess + " is too low.");
                SwingUtilities.updateComponentTreeUI(messageJLabel);
            }// end if

[B]//            Guesses++;
//            message3JLabel.setText("Enter guess #  " + Integer.toString(Guesses));[/B]

            if (Guess == number) {
                messageJLabel.setText("Congratulations!  You guessed my number!");
                getContentPane().setBackground(Color.YELLOW);
                message2JLabel.setText("");

                SwingUtilities.updateComponentTreeUI(messageJLabel);
[B]//                Guesses++;[/B]

                message3JLabel.setText("# of guesses = " + Integer.toString(Guesses));
                SwingUtilities.updateComponentTreeUI(message3JLabel);
                guessInputJTextField.setEditable(false);
            } [B]else {
                Guesses++;
                message3JLabel.setText("Enter guess #  " + Integer.toString(Guesses));
            }[/B]

            guessInputJTextField.setText("");
        }
    }

The explanation I could think of, concerning the problem of the background turning blue after the first guess, is based on two facts:

  1. The old guess is initialized to zero (GuessOld = 0).
  2. The code decides according to two absolute differences:
    • Math.abs(number - Guess)
    • Math.abs(number - GuessOld)

Example:
1. Say the number to be guessed is 20 (number = 20).
2. The user writes his/her guess.
3. Say the user's guess is number 500 (guess = 500).
4. The code checks the absolute difference of the two (absDif = 480).
5. The code checks the absolute difference between the old guess and the number (guessOld = 0, assigned during initialization). That difference is equal to the number (number - guessOld = 20).
6. So, the code, finally checks the relationship between 480 and 20.
7. Because 480 > 20, the second if of the "actionPerformed()" method of the "GuessHandler" inner class gets executed
(

if (Math.abs(number - Guess) > Math.abs(number - GuessOld))

).
8. As a result, the background's color is set to blue.

commented: This is one of the best responses I've ever gotton. Very thourough and very helpful!!! +1

Hi! Thanks alot! It seems to be working every time now. I still want to tweak the format of the frame so I'll be running it multiple times again. Hopefully I don't see it pop up blue on the first time again. I doubt I will. You're explanation was VERY thorough and understandable. Thank you very much for taking the time to explain it. I think at one point I must have almost had it because I know one time before I put it back, I had:

if (Guesses == 1)  
{
                getContentPane().setBackground(Color.RED);
                message2JLabel.setText("You're getting warmer!");
                SwingUtilities.updateComponentTreeUI(message2JLabel);
}

and then the If/else statements that are already there. I guess simply combining it with the other "if" with the OR made the difference. Anyway, it makes me feel better to see that at one point I almost had it.

As for the counter problem. I had noticed that after I had made my last post and gotten that fixed pretty easily. I suppose I should have reposted to mention that but thank you anyway for being so observant and helpful. I think it's all fixed now, thanks to your help. Like I said, I'm being a little picky now and want to change the format a little bit so I'll wait until I'm completely done before I mark this as solved but again, thanks to you, I think it is now. Thanks again!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.