繁体   English   中英

将 Java 结果导出到文本文件

[英]Exporting Java results to text file

你好,我所在的班级,需要将我的代码(计算联邦和州税)的结果导出到文本文件中。 我试过四处浏览寻求帮助,但我似乎无法得到它。 请帮忙!

public class FedStateTax {    

public static void main(String[] args) {

    String tn = javax.swing.JOptionPane.showInputDialog("Please enter your name.");
    String fn = javax.swing.JOptionPane.showInputDialog("Enter income value");


        int income = Integer.parseInt(fn);
        double sax = 0;
        double tax = 0;

        if (income <= 50000)
            tax = income * 0.10;
        else if (income <= 100000)
            tax = income * 0.15;
        else if (income <= 150000)
            tax = income * 0.20;

        if (income <= 50000)
            sax = income * 0.05;
        else if (income <= 100000)
            sax = income * 0.10;
        else if (income <= 150000)
            sax = income * 0.15;


        if (income <=  50000)
            System.out.println("Federal tax is: $" + tax);
        else if (income <= 100000)
            System.out.println("Federal tax is: $"+ tax);
        else if (income <= 150000)
            System.out.println("Federal tax is: $"+ tax);

        if (income <=  50000)
            System.out.println("State tax is: $" + sax);
        else if (income <= 100000)
            System.out.println("State tax is: $"+ tax);
        else if (income <= 150000)
            System.out.println("State tax is: $"+ tax);


}
}

据我了解,您想将税务数据写入文件。 那你为什么不直接使用:

try {
    Files.write(Paths.get("output.txt"), Arrays.asList("Tas is : " + tax));
} catch (IOException e) {
    e.printStackTrace();
}

Files.write 方法属于 java.nio 包,它接受Path作为第一个参数和可枚举字符串作为第二个参数,并将它们逐行写入文件。

您不应该记得,它会覆盖现有文件。 如果你只想追加你应该添加第三个参数 StandartOpenOption 如下:

    Files.write(Paths.get("output.txt"), Arrays.asList("Tas is : " + "5", "2"), StandardOpenOption.APPEND);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM