Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    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

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    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.

  • Users who have thanked Fou-Lu for this post:

    nglwthnati2de (10-05-2012)

  • #3
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    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.

  • #4
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    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.

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    GuessGame is already a JFrame; add all your components directly to it instead of creating mainFrame within it.

  • Users who have thanked Fou-Lu for this post:

    nglwthnati2de (10-05-2012)

  • #6
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •