user2863681 user2863681 - 7 months ago 11
Java Question

Output written to screen then to output file?

Basically I had to read in some data from an input file and do some calculations to calculate the total-staff cost per unit, the input shown below in the following format

<shop unit>
<sales assistants>
<hours> <rate>

Unit One
4
32 8
38 6
38 6
16 7

Unit Two
0

Unit Three
2
36 7
36 7


Goes upto 9 shop units..

I then had to allow a user input which is the "Recommended maximum"(RM) and compare it with the total staff costs per unit. If the total staff cost per unit is less than or equal to RM then the details must be written to the screen and to an output text file called results.txt. If the amount is larger than RM then the results must be written to the screen only.
Anyways here is my code below, and the bit im having problems with is the output mentioned above, Only shop unit 9 is printing to the output file and most of the time nothing prints to the console:

if (total > reccomended_max) {
System.out.println("The total staff wages for " + Unitnum + " is £" + total + ", therefore it is larger than the RM");
} else if (total == reccomended_max) {
System.out.println("The total staff wages for " + Unitnum + " is £" + total + ", therefore it is equal to the RM");
} else {
System.out.println("The total staff wages for " + Unitnum + " is £" + total + ", there it is less than the RM");
}


I have shortened my code, because it has a lot of else if statements, What design pattern is suitable for removing many if and else or else if statements?

Answer

Don't delegate System.out! Instead, simply write the result to both streams if required:

if (total > reccomended_max){
    String message = "The total staff wages for " + ...;
    try (PrintStream out = new PrintStream(new FileOutputStream("output.txt", true))) {
        out.println(message);
    } // here, the stream will be automatically flushed and closed!

    System.out.println(message);
} else {
    System.out.println("The total staff wages for " + Unitnum + " is £" +total + ", therefore it is lower than the RM");
}