import java.util.*;
import java.io.*;
import java.lang.*;
public class CreateFile {
final Formatter x;
public void openFile() {
try {
x = new Formatter("testing.txt");
System.out.println("File created");
} catch (Exception e) {
System.out.println("You got an error");
}
}
public void addRecords() {
x.format("%s%s%s", "20", "bucky", "roberts");
}
public void closeFile() {
x.close();
}
}
我收到错误“无法为变量 x 赋值”。我不确定为什么“最终格式化程序 x;”没有转移。
最佳答案
final
关键字可防止您重新分配变量 x
。您可以删除 final
关键字或在声明中正确进行初始化:
final Formatter x = new Formatter("testing.txt");
但是由于Formatter的构造函数会抛出异常,所以我们需要间接赋值:
public class CreateFile {
final Formatter x = getFormatter();
private static Formatter getFormatter() {
Formatter res = null;
try {
res = new Formatter("test.txt");
} catch (FileNotFoundException e) {
}
return res;
}
}
关于java - 格式化程序类无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25881880/