Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-04-2012, 10:42 PM   PM User | #1
nglwthnati2de
New to the CF scene

 
Join Date: Sep 2012
Posts: 5
Thanks: 2
Thanked 0 Times in 0 Posts
nglwthnati2de is an unknown quantity at this point
Looking for a little insight as to why this does not work

Hi guys I am having a problem with my Java code. I was hoping maybe someone here could help me out with it. I am totally new to programming with java so don't be too harsh.
This is supposed to be a guessing game where the user guesses the number. Here are the specifics:
Your program chooses the number to be guessed by selecting an integer at random in the range 11000. The program then displays the following in a label.

I have a number between 1 and 1000 -- can you guess my number?

Please enter your guess: ____________________

A JTextField should be used to input the guess. A JButton must be provided to allow the user to press each time a guess is entered. As each guess is input, the background color should change to either red or blue. Red indicates that the user is getting warmer, and blue indicates that the user is getting colder. A JLabel should display either Too High or Too Low to help the user zero in on the correct answer. When the user gets the correct answer, Correct! should be displayed, and the JTextField used for input should be cleared and changed to be uneditable. Also, a JButton should be provided to allow the user to play the game again. When the New Game JButton is clicked, a new random number should be generated and the input JTextField changed to be editable. A JButton must be provided to allow the user to exit the application. Also provide a count of the number of guesses the user entered when the correct number is guessed.

This is the code I have put together:

Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GuessGame extends JFrame
{
	private static JFrame mainFrame;
	private static JButton tryButton;
	private static JButton newgameButton;
	private static JButton exitButton;
	private static JTextField guessField;
	private static JLabel guessLabel;
	private static JLabel headerLabel;
	private static JTextField results;
	private static JPanel panel;
	private static int randomNumber;
	
	
	public GuessGame() 
	{
		mainFrame = new JFrame ("Guessing Game");
		tryButton = new JButton ("Try the number");
		exitButton = new JButton ("Exit");
		newgameButton = new JButton ("New Game");
		guessLabel = new JLabel ("Enter your guess:");
		headerLabel = new JLabel(
				"<html>I have a number between 1 and 1000,<br>can you guess the number?</html>");
		guessField = new JTextField(5);
		results = new JTextField(25);
		panel = new JPanel();
		

		mainFrame.addWindowListener(new WindowAdapter() 
		{
			public void windowClosing(WindowEvent e) 
			{
				System.exit(0);
			}
			
		});

		TryButtonHandler tbHandler = new TryButtonHandler();
		tryButton.addActionListener(tbHandler);

		ExitButtonHandler eHandler = new ExitButtonHandler();
		exitButton.addActionListener(eHandler);

		NewGameButtonHandler ngHandler = new NewGameButtonHandler();
		newgameButton.addActionListener(ngHandler);

		tryButton.setMnemonic('T');
		exitButton.setMnemonic('E');
		newgameButton.setMnemonic('N');

		results.setBackground(Color.WHITE);
		results.setEditable(false);
		results.setText("Too high/Too low message will go here!");

		Container c = mainFrame.getContentPane();
		c.setLayout(new BorderLayout());
		panel.setLayout(new FlowLayout(FlowLayout.CENTER));

		panel.add(headerLabel);
		panel.add(guessLabel);
		panel.add(guessField);
		panel.add(tryButton);
		panel.add(exitButton);
		panel.add(newgameButton);
		panel.add(results);
		c.add(panel);

		mainFrame.setSize(325, 210);
		mainFrame.setVisible(true);
	}

	public class TryButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			int userInput=0;
			int diff;
			int Difference;
			
			try 
			{
				userInput = Integer.parseInt(
						guessField.getText().trim());
			} 
			
			catch (Exception ex)
			{
				results.setText("Enter a VALID number!");
				return;
			}
			
			if (userInput == randomNumber){
				JOptionPane.showMessageDialog(null, "CONGRATULATIONS! You got it!!",
						"Random Number: " + randomNumber, JOptionPane.INFORMATION_MESSAGE);
				randomNumber = new Random().nextInt(1000) + 1;
				return;
			}
			
			if (userInput > randomNumber){
				results.setText( "Too High. Try a lower number." );
				diff=userInput - randomNumber;
				Difference=Math.abs(diff);
			} 
			
			else 
			{
				results.setText( "Too Low. Try a higher number." );
				diff=randomNumber - userInput;
				Difference=Math.abs(diff);
			}
			
			if(Difference<=25)
			{
				results.setText("You're getting colder!");
				setBackground(Color.blue);
				repaint();
			}

			if(Difference<=10){
				results.setText("You're getting warmer!");
				setBackground(Color.red);
				repaint();
			}

			
		}
		
	}

	static class ExitButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			System.exit(0);

		}

	}

	public class NewGameButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			SwingUtilities.invokeLater(new Runnable() 
			{
				public void run() 
				{
					GuessGame GuessNumber = new GuessGame();
					GuessNumber.setVisible(true);
				}
				
			});
		}

	}

	private void setBackgroundColor(Color color)
	{
		panel.setBackground(color);
		panel.setBackground(color);
		panel.setBackground(color);
	}
	
	
	public static void main(String[] args)
	{
		new GuessGame();
	}
			
		
}
I don't get any errors but it's not behaving right. For instance I don't believe the random number is generating and the colors of the panel don't change when they are supposed to.

I really appreciate any help I can get on this.
Thank you
nglwthnati2de is offline   Reply With Quote
Old 10-04-2012, 11:16 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,738
Thanks: 4
Thanked 2,464 Times in 2,433 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
You don't do anything to generate a random number to start with. The only time you create one is when you successfully guess the random number. So you need to generate that elsewhere during construction.
The colour changing is working properly, just not the way you want it. You are attempting to set the background of the JFrame, not the panel. Change those to panel.setBackground and it will work fine.

You should do some more evaluation of the structure here. GuessGame is a JFrame, but doesn't make any use of being as such. Instead it invokes its own JFrame and shows that, so this means you cannot call any component specific calls on the nested classes without providing an object to work with since the JFrame that would resolve to the implicit "this" of the parent wouldn't have any impact on the existing gui. Also, these properties are all static. If you leave them as such, then it will impact on the new game functionality which spawns a new frame. Both of these then share the same random number and all the components will be the same. It'll likely break the event handlers too I'd expect since the focusing will become. . . bizarre.

Move the control of the guessing to the GuessGame. Let the trybuttonhandler simply call the GuessGame methods.
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
nglwthnati2de (10-05-2012)
Old 10-05-2012, 12:07 AM   PM User | #3
nglwthnati2de
New to the CF scene

 
Join Date: Sep 2012
Posts: 5
Thanks: 2
Thanked 0 Times in 0 Posts
nglwthnati2de is an unknown quantity at this point
guessing game

Ok great thank you so much. I have no idea what some of this means but at least i have something to go on. Instead of wandering aimlessly trying to figure out what is wrong, I can wander aimlessly and figure out how to fix what is wrong (LOL - JK - This is a homework assignment so what you gave is exactly what I needed). Thank you so much for your help.
nglwthnati2de is offline   Reply With Quote
Old 10-05-2012, 12:32 AM   PM User | #4
nglwthnati2de
New to the CF scene

 
Join Date: Sep 2012
Posts: 5
Thanks: 2
Thanked 0 Times in 0 Posts
nglwthnati2de is an unknown quantity at this point
About your answer

I just have one question about your reply though, if you don't mind.
What is meant by this:

" GuessGame is a JFrame, but doesn't make any use of being as such. Instead it invokes its own JFrame and shows that, so this means you cannot call any component specific calls on the nested classes without providing an object to work with since the JFrame that would resolve to the implicit "this" of the parent wouldn't have any impact on the existing gui."

This part left me a little lost.
nglwthnati2de is offline   Reply With Quote
Old 10-05-2012, 12:58 AM   PM User | #5
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,738
Thanks: 4
Thanked 2,464 Times in 2,433 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
GuessGame is already a JFrame; add all your components directly to it instead of creating mainFrame within it.
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
nglwthnati2de (10-05-2012)
Old 10-05-2012, 02:24 AM   PM User | #6
nglwthnati2de
New to the CF scene

 
Join Date: Sep 2012
Posts: 5
Thanks: 2
Thanked 0 Times in 0 Posts
nglwthnati2de is an unknown quantity at this point
Thanks I got it now. It works great. It may not be completely structured as it should be, but it is working. I am hoping pretty soon all of this is just going to come together.
nglwthnati2de is offline   Reply With Quote
Reply

Bookmarks

Tags
guessing game, java

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:31 AM.


Advertisement
Log in to turn off these ads.