java - 格式化程序类无法正常工作

标签 java formatter

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/

相关文章:

java - Eclipse 中的导出窗口上没有可运行的 JAR 文件选项

Java + PDFBox 无法在 Linux 服务器上运行

javascript - 渲染图表后,从图表对象更改 Highcharts 工具提示格式化程序

visual-studio-code - 强制VSCode始终使用制表符作为缩进

eclipse - 从 Eclipse 格式化程序文件创建 Checkstyle 配置

swift - 我的时区中的日期字符串使日期错误

虚拟机与本地机中的 Java 应用程序性能

java - 在 Java 中按情况打破 while 循环

Java 变量无法从一个类访问到另一个类

iphone - 如何在 ios 上正确格式化货币