将Java结果导出到文本文件

时间:2018-09-22 18:35:50

标签: java export-to-text

您好,我所在的班级要求将我的代码结果(计算联邦和州税)导出到文本文件。我尝试浏览浏览以寻求帮助,但似乎无法理解。请帮忙!

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


}
}

1 个答案:

答案 0 :(得分:-1)

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

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