简体   繁体   English

将 Java 结果导出到文本文件

[英]Exporting Java results to text file

Hello for my class that I am in, it is required that the results of my code (calculating federal and state tax) be exported to a text file.你好,我所在的班级,需要将我的代码(计算联邦和州税)的结果导出到文本文件中。 I have tried browsing around for help but I just can't seem to get it.我试过四处浏览寻求帮助,但我似乎无法得到它。 Please help!请帮忙!

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);


}
}

As I understand you want to write tax data into file.据我了解,您想将税务数据写入文件。 So why don't you just use :那你为什么不直接使用:

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

Files.write method belongs to java.nio package and it accepts Path as first parameter and enumerable string as second parameter and writes them to file line by line. Files.write 方法属于 java.nio 包,它接受Path作为第一个参数和可枚举字符串作为第二个参数,并将它们逐行写入文件。

You should not remember, it overrides the existing file.您不应该记得,它会覆盖现有文件。 If you want to only append you should add third parameter StandartOpenOption as below:如果你只想追加你应该添加第三个参数 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