简体   繁体   中英

GuessGame can't get program to output messages

I got the widow and the buttons into the GUI but for the life of me I can't get anything to output. I am suppose to enter a guess, and from a random number the game generates. It is suppose to tell me if I'm too high, too low or correct. Also, if it is not correct it's supposed to tell me if I am warm or cold. If any one could point me in the right direction on this I would be grateful. I don't know what I'm doing wrong on this. I have researched different topics but with the different ways to solve this problem none match what I was looking for.

Here's the code:

//all necessary imports

public class GuessGame extends JFrame 
{
    private static final long serialVersionUID = 1L;
    private JFrame mainFrame;
    private JTextField guessField;
    private JLabel message1;
    private JLabel message2;
    private JLabel message3;
    private JLabel message4;
    private JLabel guessLabel;
    private JLabel tooHigh;
    private JLabel tooLow;
    private JButton guessButton;
    private JButton newGame;
    private JButton exitButton;
    private int randomNum = 0;
    private final int MAX_NUM = 1000;
    private final int MIN_NUM = 1;
    private int guessCount;
    private int lastDistance;

    public GuessGame()
    {
        mainFrame = new JFrame();
        guessField = new JTextField(4);
        message4 = new JLabel("I have a number between 1 and 1000 -- can you guess my number?") ;
        guessLabel = new JLabel("Please Enter Your Guess:");


        guessButton = new JButton("Guess");
        newGame = new JButton("New Game");
        exitButton = new JButton("Exit");

        Container c = mainFrame.getContentPane();
        c.setLayout(new FlowLayout());
        c.setBackground(Color.CYAN);

        c.add(message4);
        c.add(guessLabel);
        c.add(guessField);
        c.add(guessButton);
        c.add(newGame);
        c.add(exitButton);

        newGame.setMnemonic('N');
        exitButton.setMnemonic('E');
        guessButton.setMnemonic('G');

        mainFrame.setSize(420, 300);//Sets width and height of Window
        mainFrame.setVisible(true);//Allows GUI to be visible
        mainFrame.addWindowListener(new WindowAdapter()

        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });

        GuessButtonsHandler gHandler = new GuessButtonsHandler();
        guessField.addActionListener(gHandler);

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

        NewGameButtonsHandler nHandler = new NewGameButtonsHandler();
        newGame.addActionListener(nHandler);
    }

    class GuessButtonsHandler implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {

            Random rand = new Random();

            int guess = 0;
            int currDistance = 0;
            boolean correct = false;
            guess = Integer.parseInt(guessField.getText());//Converts String to Integer

            if(guessCount == 0)
            {
                lastDistance = MAX_NUM;
            }

            if(guess >= MIN_NUM && guess <= MAX_NUM)
            {
                guessCount += 1;
            }

            if(guess > randomNum)
            {
                 tooHigh.setText("Number To High!!!");
                 guessCount += 1;
            }

            else if(guess > randomNum)
            {
                 tooLow.setText("Number To Low!!!");
                 guessCount += 1;
            }

            else 
            {
                correct = true;
                message2.setText("Correct!!!");
                message2.setBackground(Color.GREEN);
                guessField.setEditable(false);
            }

            if(!correct)
            {
                currDistance = Math.abs(guess - randomNum);
            }

            if(currDistance <= lastDistance)
            {
                message3.setText("You are getting warmer!!!");
                mainFrame.add(message3).setBackground(Color.RED);

            }

            else
            {
                message4.setText("You are getting colder!!!");
                mainFrame.add(message4).setBackground(Color.BLUE);
            }

                lastDistance = currDistance;
                randomNum = rand.nextInt(1000) + 1;
        }

    }

    class NewGameButtonsHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            Random rand = new Random();
            randomNum = rand.nextInt(1000) + 1;
            guessCount = 0;
        }
    }

    class ExitButtonsHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
}

public class GuessGameTest {

    public static void main(String[] args) 
    {
        new GuessGame();
    }
}

You need to:

  1. Add gHandler as a listener to the button too, not only to the text field:

     guessField.addActionListener(gHandler); guessButton.addActionListener(gHandler); 

    Keeping it in the text field too is a good idea: then the guess can be triggered by pressing enter too, not just clicking the button (this part actually works in your code).

  2. You need to initialize the message labels, and add them somewhere. You have additions commented out, but the initializations are missing.

  3. You don't really need labels for all possible messages. You want to display only a message for too high, too low, or correct guess at a time. Not two or more simultaneously. So one field is enough, just set the correct text.

  4. You have the condition inverted when checking too low numbers.

  5. You generate a new random number after each guess, so the "getting warmer" messages are not very useful. Also you don't need to create a new Random object every time you want a new random number.

Possibly others too, but hopefully these help you forward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM