【发布时间】:2015-03-16 09:26:00
【问题描述】:
我有一个问题。我创建了一个将添加两个随机数的程序。我正在尝试将Math.random() 放在JTextField 中,但它不会出现。顺便说一下,这是我的代码:
公共类 RandomMathGame 扩展 JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
不要介意lvl2 和lvl3,因为它在lvl1 中是一样的。而且,我想循环它们 10 次。我在放置这些代码时遇到了困难。有人能帮我吗?谢谢你的帮助。 :)
【问题讨论】:
-
我认为永远不会执行 lvl1 动作。可以调试一下吗?
-
我试过了。但是没有出现随机数。
-
random1正在生成对吗?你见过调试模式吗? -
random1已生成,但没有出现整数。 -
我认为你的逻辑有问题。也许您在
Integer.valueOf行有异常,或者您的 for 循环没有在设置值的地方运行。再次检查你的逻辑,做调试,你可以破解它..