如何从另一个类访问变量的最后一个值?程序运行30秒,结束30秒,它打印变量。
游戏类:
public class Game {
public int true_num = 0, false_num = 0;
public Game() throws InterruptedException, IOException {
new TimerDemo(30);
while (true) {
play(); // true_num/false_num are changed in this method.
}
}
}
TimerDemo类:
public class TimerDemo {
Toolkit toolkit;
Timer timer;
public TimerDemo(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
@Override
public void run() {
System.out.println("Time's up!");
JLabel lb = new JLabel("true_num = " + true_num
+ " and " + "false_num = " + false_num);
lb.setFont(new Font("Arial", Font.BOLD, 18));
UIManager.put("OptionPane.minimumSize", new Dimension(150, 90));
JOptionPane.showMessageDialog(null, lb, "aaa", 1);
toolkit.beep();
System.exit(0);
}
}
}
如何在Game类的play函数中访问变量的最后一个值?调用类导致play function
再次运行,不应该。
答案 0 :(得分:0)
没有Game的参考,我在游戏中添加了Game.total并定义了volatile总数。
在TimerDemo中:
public void run() {
System.out.println("Time's up! Total = " + Game.total + "true_num =" + Game.true_num + "false_num =" + Game.false_num);
}
在游戏中:
public static volatile int true_num = 0, false_num = 0, total = 0;