Search code examples
javatimertask

Java accessing local variable in enclosed scope


I was having some problem with TimerTask in java. Basically what I am trying to do is for each session to compute something, I set one minute time frame, once the time is up, I will prompt users to input whether to start another session. Here is what I have tried:

    String toCont = "";
    Scanner scanner = new Scanner(System.in);
    
    do {
        long delay = TimeUnit.MINUTES.toMillis(1);
        Timer t = new Timer();
        int marks = startSession(); // function to compute some marks
        
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Time's up!");
                System.out.print("Do you wished to start a new game? (Y/N): ");
                toCont = scanner.next();
            }
        };
        t.schedule(task, delay);

    } while (toCont.equals("y") || toCont.equals("Y"));

However, I am having some syntax error on the toCont variable in run(). Error message as such "Local variable toCont defined in an enclosing scope must be final or effectively final". Any ideas how can I resolve this? Thanks!


Solution

  • Make the variable into a final single-element array.

    final String[] toCont = {
        ""
    };
    Scanner scanner = new Scanner(System.in);
    
    do {
        long delay = TimeUnit.MINUTES.toMillis(1);
        Timer t = new Timer();
        int marks = startSession(); // function to compute some marks
    
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Time's up!");
                System.out.print("Do you wished to start a new game? (Y/N): ");
                toCont[0] = scanner.next();
            }
        };
        t.schedule(task, delay);
    
    } while (toCont[0].equals("y") || toCont[0].equals("Y"));