x=(int)Math.random()*100;//错误写法 ,最终结果总是0
这个写法是错误的,因为Java的运算符优先级问题。(int)Math.random()
会先把Math.random()
的结果(一个0.0到1.0之间的小数)强制转换成整数(结果总是0),然后再乘以100,所以最终x总是0。
正确的应该是:
x = (int)(Math.random() * 100);
这样就会先计算Math.random() * 100
(得到一个0.0到100.0之间的小数),然后再转换成整数(结果就是0到99之间的随机整数)。
这些小细节一定得注意!!!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TestI {
int i = 1;
int sum = 0;
int random=0;
TestI() {
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
random=(int)(Math.random()*10);
sum = i+random;
System.out.print(" sum = " + sum);
if (sum > 8) {
random=-10;
i = -1;
System.out.println();
} else if (sum < 0) {
random=0;
i = 1;
System.out.println();
}
}
});
timer.start();
JFrame frame = new JFrame("Timer Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
// 使用SwingUtilities确保在事件调度线程中运行
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestI();
}
});
}
}