Exporting Java results to text file

744 views Asked by At

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


}
}
1

There are 1 answers

2
Emre Savcı On

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 Pathas first parameter and enumerable string as second parameter and writes them to file line by line.

You should not remember, it overrides the existing file. If you want to only append you should add third parameter StandartOpenOption as below:

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