1

How to access to the last value of the variable from another class? The program runs in 30 seconds and the end of 30 seconds, It prints variables.

Game class:

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 class:

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);
        }
    }
}

How to access the last value of the variables in the play function in Game class? call class is caused play function runs again that should not.

ParisaN
  • 1,816
  • 2
  • 23
  • 55
  • Give TimerDemo a reference to the Game instance e.g. via the constructor `new TimerDemo(30, this);` Also `true_num` should technically be `volatile` if you want to guarantee the timer task can read the actual value – zapl Apr 25 '18 at 20:55
  • @zapal, I did and it worked: `private final Game get_val; private RemindTask(Game1 aThis) { get_val = aThis; }` and `get_val.true_num`. but Game runs again after end of 30 seconds. – ParisaN Apr 25 '18 at 21:41

1 Answers1

0

Without reference from Game, I adding Game.total and defined volatile total in Game.

In TimerDemo:

public void run() {
     System.out.println("Time's up! Total = " + Game.total + "true_num =" + Game.true_num + "false_num =" + Game.false_num);
}

In Game:

public static volatile int true_num = 0, false_num = 0, total = 0;
ParisaN
  • 1,816
  • 2
  • 23
  • 55