输出写入屏幕然后输出文件?

时间:2013-11-28 21:14:36

标签: java loops if-statement console output

基本上我必须从输入文件中读取一些数据并进行一些计算以计算每单位的总人员成本,输入如下所示,以下格式

<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

最多9个商店..

然后,我必须允许用户输入“推荐最大值”(RM),并将其与每个单位的总人员成本进行比较。如果每个单位的员工总成本小于或等于RM,则必须将详细信息写入屏幕和名为results.txt的输出文本文件。如果金额大于RM,则结果必须仅写入屏幕。 无论如何这里是我的代码如下,并且我遇到的问题是上面提到的输出,只有商店单元9正在打印到输出文件,并且大部分时间都没有打印到控制台:

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

我缩短了我的代码,因为它有很多其他if语句,什么设计模式适合删除许多if和else或if语句?

1 个答案:

答案 0 :(得分:0)

不要委托System.out!相反,如果需要,只需将结果写入两个流:

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");
}
相关问题