Java 访问封闭范围内的局部变量

Java accessing local variable in enclosed scope

我在 java 中遇到了 TimerTask 的问题。基本上我想要做的是为每个会话计算一些东西,我设置一分钟的时间范围,一旦时间到了,我会提示用户输入是否开始另一个会话。这是我尝试过的:

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

但是,运行() 中的 toCont 变量存在一些语法错误。这样的错误消息“在封闭范围内定义的局部变量 toCont 必须是最终的或实际上是最终的”。有什么想法可以解决这个问题吗?谢谢!

将变量变成最终的 single-element 数组。

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

要在内部 class 中使用变量,您必须将其声明为 final。 在你的 do while 循环中添加这个(解决方法)

do {
        long delay = TimeUnit.MINUTES.toMillis(1);
        final Integer innertoCont = new Integer(toCont);
        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): ");
                innertoCont = scanner.next();
            }
        };
        t.schedule(task, delay);

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