gpt4 book ai didi

Java 错误 : Need to declare a variable as final in actionPerformed, 但我需要更改它

转载 作者:行者123 更新时间:2023-12-01 18:59:13 26 4
gpt4 key购买 nike

此问题已由 Robin 解决。谢谢罗宾!

我想要做的背后的想法是制作一个计时器,每 X 秒执行一次操作,但 X 必须在使用之间进行更改。

现在我正在这样做:

 try {
final FileWriter fstream = new FileWriter("timetest.log");
final BufferedWriter out = new BufferedWriter(fstream);

ActionListener task_performer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
critical_requests[0]++;
try {
System.out.println("DEBUG: Critical Section requests: " + critical_requests[0] + "\n");
out.write("Critical Section request:\t" + critical_requests[0] + "\n");
} catch (IOException e) {
System.out.println(e.getMessage() + "\n");
}
((Timer)evt.getSource()).setDelay( 150 + (rand.nextInt(10) * time_unit ));
}
};
new Timer(wait_delay, task_performer).start();
System.out.println("Entering while loop\n");
while(true) {
if(critical_requests[0] >= 60){
try {
out.close();
} catch (IOException e) {
System.out.println("Close failed for some reason:\t" + e.getMessage() + "\n");
System.exit(-1);
}
System.exit(0);
}
//System.out.println("" + critical_requests[0] + "\n"); // Debug
critical_requests[0] = critical_requests[0]; // Java is an insane language and it requires me to have this line here
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(-1);
}

我得到的错误是:

local variable is accessed from within inner class; needs to be declared final

我尝试将其中一些设为最终值,但随后我无法更改监听器内部的值。另外,有些变量没有意义成为最终变量(BufferedWriter 输出、rand)。

所有 5 个编译器错误是: 局部变量 rand 从内部类内部访问;需要宣布最终out、rand 和 wait_delay 各一个,关键请求各两个。

如何协调这个问题?

最佳答案

查看您的代码,问题出在 wait_delayritic_requests 变量。

  1. 没有真正需要在 ActionListener 内更改它。您必须在 Timer 上再次设置它,然后它才会对 Timer 的延迟产生任何影响
  2. 每次更改 wait_delay 变量时创建一个新的 Timer 对象将导致产生大量 Timer 实例,每个实例都会持续运行Timer 默认情况下会重复。只有当您调用了 setRepeats( false ) 时,它们才会真正停止。查看您的评论(应该是问题的一部分),您想更新 Timer
  3. 的延迟
  4. 如果您确实需要更改 ActionListener 内的 ritic_requests 变量,您可以将其存储在最终数组中

所以我建议将您的代码更改为类似的内容

final int[] critical_requests = new int[]{ 0 };
final Outputstream out = ...;
ActionListener task_performer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
critical_requests[0] = critical_requests[0] + 1;
try {
out.write("Critical Section request:\t" + (critical_requests[0]) + "\n");
((Timer)evt.getSource()).setDelay( 10 + (rand.nextInt() % 10) );
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
}
};
Timer the_one_and_only_timer = new Timer( wait_delay, task_performer );

关于Java 错误 : Need to declare a variable as final in actionPerformed, 但我需要更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com