Welcome to Dream.In.Code
Become a Java Expert!

Join 149,478 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,518 people online right now. Registration is fast and FREE... Join Now!




Guessing Game Problem

 
Reply to this topicStart new topic

Guessing Game Problem

H(alo)oNdA 5thG
3 May, 2007 - 03:06 PM
Post #1

New D.I.C Head
*

Joined: 3 May, 2007
Posts: 2


My Contributions
So i'm new to this thread i figured i would let some people view my code to see if they figure out my last problem before i turn in this program. The last thing i need my program to do is change the background color Red if the number the user guesses is getting closer to the Random number or Blue if they are guessing further away. Take a look.

Ooo and the correct number is displayed by the "New Game" button just for a check


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 Test extends JFrame
{
    int GuessOld = 0;    
    private int number; // number chosen by application
    private JTextField guessInputJTextField; // for guessing
    private JLabel prompt1JLabel; // first prompt to user
    private JLabel prompt2JLabel; // second prompt to user
    private JLabel messageJLabel; // displays message of game status
    private JLabel random1;
    private JButton newGameJButton; // creates new game
    private Color background; // background color of application

        // set up GUI and initialize values
        public Test()
        {
            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? Enter your Guess:" ); // prompt user
                add(prompt2JLabel);

                guessInputJTextField = new JTextField( 5 ); // to enter guesses
                guessInputJTextField.addActionListener( new GuessHandler( ) );
                add(guessInputJTextField);
        
                messageJLabel = new JLabel( "" );
                add(messageJLabel);


                newGameJButton = new JButton( "New Game" ); // button with text
                add ( newGameJButton ); // add newGame button to JFrame
                
                Random generator = new Random();
                int number = generator.nextInt(1001);
                
                random1 = new JLabel( " " + number);
                add( random1 );
                
                newGameJButton.addActionListener(

                        new ActionListener() // anonymous inner class
                        {
                        public void actionPerformed( ActionEvent e )
                        {
                                                
                            guessInputJTextField.setText("");
                            Random generator = new Random();
                            int number = generator.nextInt(1001);
                            random1.setText("" + number );
                            SwingUtilities.updateComponentTreeUI(random1);
                            messageJLabel.setText("");
                            guessInputJTextField.setEditable(true);


                            
                            
                        } // 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()
        {
    
        } // end method theGame

        // change background color
        public void paint( Graphics g )
        {
                super.paint( g );
                getContentPane().setBackground( background ); // set background
        } // end method paint
        public void distance()
        {
            int Guess;
            Guess = Integer.parseInt(guessInputJTextField.getText());
            if ( Math.abs( number - Guess ) < Math.abs( number - GuessOld) )
                // Hotter
                setBackground(Color.RED);
            
                else
                                    
                // Colder
                setBackground(Color.BLUE);
                
                GuessOld = Guess;
        }
        


            // react to new guess
        class GuessHandler implements ActionListener
        {
            public void actionPerformed( ActionEvent e )
            {
                
            int Guess;
               
               Guess = Integer.parseInt(guessInputJTextField.getText());
               number = Integer.parseInt(random1.getText());
               
              
                if ( Guess >= number )
                {
                    messageJLabel.setText( "Too High." );
                    SwingUtilities.updateComponentTreeUI(messageJLabel);
                }
                
                if( Guess <= number )
                    {
                                    
                        messageJLabel.setText( "Too Low." );
                        SwingUtilities.updateComponentTreeUI(messageJLabel);
                    
                } // end if
                    
                        
                
                if ( Guess < number + 1 && Guess > number-1 ) // guess is too low
                        {
                            messageJLabel.setText( "Correct!" );
                            SwingUtilities.updateComponentTreeUI(messageJLabel);
                            guessInputJTextField.setEditable(false);
                            
                                
                                

                        }
                            
                    
                    
                }

            }
        
    
            
            

        }

                




CODE
import javax.swing.JFrame;


public class GuessgameTest
    {
    public static void main(String args[]) throws Exception
    {
        Test guessgame = new Test();
        guessgame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        guessgame.setSize(550, 150);
        guessgame.setVisible(true);
        
    }

}

User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Guessing Game Problem
5 May, 2007 - 06:30 PM
Post #2

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
don't forget to use: getContentPane() instead of just adding things to the frame itself. The JFrame is not actually meant to hold items itself other than panels, the default is the content pane. This code piece should precede all add lines and the setLayout line, and your background color changes as well.

also variables should not start with capital letters. The only exception is a static variable which is made of ALL capital letters.

this line does not handle your string having spaces... which i ran into many times, so make it (with a trim):
number = Integer.parseInt((random1.getText()).trim());


Your algorithm is correct, but the if statements should have { and } since you are using an else... the only time {} should ever be left out is when there is a 1 line if statement and only 1 line.

Remove the distance method and make your actionHandler:
CODE


            public void actionPerformed( ActionEvent e )
            {
                
            int Guess;
              
               Guess = Integer.parseInt(guessInputJTextField.getText());
               number = Integer.parseInt((random1.getText()).trim());
              
              if ( Math.abs( number - Guess ) < Math.abs( number - GuessOld) ){
                // Hotter
                getContentPane().setBackground(Color.RED);
            }
            else{
                                    
                // Colder
                getContentPane().setBackground(Color.BLUE);
            }
                GuessOld = Guess;
                if ( Guess >= number )
                {
                    messageJLabel.setText( "Too High." );
                    SwingUtilities.updateComponentTreeUI(messageJLabel);
                }
                
                if( Guess <= number )
                    {
                                    
                        messageJLabel.setText( "Too Low." );
                        SwingUtilities.updateComponentTreeUI(messageJLabel);
                    
                } // end if
                    
                        
                
                if ( Guess < number + 1 && Guess > number-1 ) // guess is too low
                        {
                            messageJLabel.setText( "Correct!" );
                            SwingUtilities.updateComponentTreeUI(messageJLabel);
                            guessInputJTextField.setEditable(false);
                            
                                
                                

                        }
                            
                    
                    
                }

            }


please work on your tabbing, it is very inconsistent and hard to read.

If you need any further help, i have finished the program as you described in full.
User is offlineProfile CardPM
+Quote Post

H(alo)oNdA 5thG
RE: Guessing Game Problem
26 May, 2007 - 06:38 PM
Post #3

New D.I.C Head
*

Joined: 3 May, 2007
Posts: 2


My Contributions
Thx biggrin.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 03:54PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month