猜猜我的号码游戏

时间:2014-06-19 18:44:55

标签: java

我正在学习java并且正在制作一个游戏Guess My Number,其中计算机选择随机数,对于随机数,该随机数被声明为int rNumber。我创建了2个按钮,猜测并退出,当玩家在标签旁边的texfield中输入一个数字并点击GUESS按钮然后它会显示我在GuessButtonHandler中提到的消息。但是这里我的GUESS按钮不起作用。我的代码中没有错误我可以看到JFrame但是猜猜按钮不起作用。你能告诉我我的错吗?请帮我。非常感谢!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GuessMyNumberGame extends JFrame
{
    public JLabel guessL, resultL;
    public JTextField guessTF, resultTF;
    public int rNumber = (int) (Math.random() * 100);

    public GuessMyNumberGame()
    {
        setTitle("Guess My Number");
        Container c = getContentPane();
        c.setLayout(new GridLayout(3,2));

        guessL = new JLabel("Guess a number between 1 & 100");
        resultL = new JLabel("Result");

        guessTF = new JTextField(15);
        resultTF = new JTextField(15);

        JButton GuessB = new JButton("Guess");
        GuessB.addActionListener(new GuessButtonHandler());

        JButton exitB = new JButton("Exit");
        exitB.addActionListener(new ExitButtonHandler());

        c.add(guessL);
        c.add(guessTF);
        c.add(resultL);
        c.add(resultTF);
        c.add(GuessB);
        c.add(exitB);

        setSize(500,900);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    class GuessButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            int a = Integer.parseInt(guessTF.getText());
            do
            {
                if(a == rNumber)
                {
                    resultTF.setText("Good Job! your Guess is perfect" +a);
                }
                else if (a < rNumber)
                {
                    resultTF.setText("your guess is lower than the random number" +a);
                }
                else
                    resultTF.setText("your guess is higher than the random number" +a);
            }
            while( a != rNumber);
        }
    }

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

    public static void main(String[] args)
    {
        GuessMyNumberGame gmn = new GuessMyNumberGame();
    }
}

1 个答案:

答案 0 :(得分:3)

删除GuessButtonHandler中的do-while循环,但保留内容。你在那个循环中没有输入,所以你会得到一个无限循环。