java中的猜数程序,我的老出现,问题,哪位高手帮忙调试,指出错误!!!在线等急求!!

2025-01-05 11:20:47
推荐回答(2个)
回答(1):

先按start按钮开始
然后就可以填如数字猜了。。按submit提交,看是否猜中。

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutFocusTraversalPolicy;

public class Test extends JFrame {
private static int randomNumber = 1895;

public static void main(String[] args) {
final JFrame frame = new JFrame();

JLabel question = new JLabel(
"I have a number between 1 and 1000 ,can you guess my number");
final JLabel hint = new JLabel("please input you number");
final JTextField tf = new JTextField(8);
JButton submit = new JButton("submit");
JButton start = new JButton("Start");

final JPanel panel = new JPanel();
panel.add(question);
panel.add(hint);
panel.add(tf);
tf.setSize(40, 80);
panel.add(submit);
panel.add(start);

frame.add(panel);

frame.setBounds(200, 200, 300, 200);
frame.setVisible(true);
frame.setLayout(new FlowLayout());

start.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
randomNumber = (int) (Math.random() * 1000 + 1);
}
});
submit.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int num = Integer.parseInt(tf.getText());
if (randomNumber != 1895) {
if (randomNumber == num) {
hint.setText("Correct!!");
tf.enable(false);
randomNumber = 1895;
} else if (num >= randomNumber) {
panel.setBackground(Color.RED);
hint.setText("Too Hign");
} else if (num < randomNumber) {
panel.setBackground(Color.BLUE);
hint.setText("Too Low");
}
}
}
});

}
}

回答(2):

actionPerformed(ActionEvent e)方法严重逻辑混乱
首先要区分事件来源
然后不是每次都要产生随机数,而是replay的时候产生随机数