Java访问封闭范围中的本地变量
我在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"));
但是,我在run()中的Tocont变量上都有一些语法错误。错误消息是这样“封闭范围中定义的本地变量Tocont必须是最终或有效最终的”。有什么想法我该如何解决?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将变量变成最终的单元素阵列。
Make the variable into a final single-element array.
要在内部类中使用变量,必须将其声明为最终。
将其添加到循环时(解决方法)中
To use a variable inside an inner class you must declare it final.
add this in your do while loop(workaround)