簡體   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