【发布时间】:2017-08-28 21:04:22
【问题描述】:
我正在尝试打印出x/mol 的百分比,但我似乎无法让它工作。我收到此错误:Local variable x defined in an enclosing scope must be final or effectively final
它说这发生在第 22 行,并且没有简单的解决方法。 java 的作用域是什么,如何将 x 添加到作用域中以便我的计时器可以读取它。
import java.math.BigInteger;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class mol {
public static void main(String[] args) {
String writable = "";
BigInteger x = new BigInteger("0");
BigInteger mol = new BigInteger("602214179000000000000000");
File file = new File("molA.txt");
BufferedWriter bw = null;
FileWriter fw = null;
Timer t;
t = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(x.divide(mol) + "%");
System.out.println(x);
}
});
System.out.println("Starting...");
t.start();
do {
writable += "a";
x = x.add(new BigInteger("1"));
} while (x.compareTo(mol) < 0);
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(writable);
System.out.println("Done");
} catch (IOException e) {
System.out.println(e);
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
t.stop();
System.out.println("Finished!");
}
}
【问题讨论】:
-
"它说这发生在第 22 行" 我们没有行号,所以请指出是哪一行代码。
-
@takendarkk 错误来自前两行
System.out.println -
让 OP 真正更新他们的问题。如果我真的需要知道行号是什么,我可以复制/粘贴到记事本++。
-
@Harald 它不是重复的,因为在这种情况下,OP *wants 能够重新分配
x,因此它不能被声明为final
标签: java