【问题标题】:Output written to screen then to output file?输出写入屏幕然后输出文件?
【发布时间】:2013-11-28 21:14:36
【问题描述】:

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

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

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

【问题讨论】:

  • 您能否格式化您的代码以使其更具可读性?
  • 你的意思是让它更具可读性?
  • 编辑您的问题并使用适当的制表符/间距。

标签: java loops if-statement console output


【解决方案1】:

不要委托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");
}

【讨论】:

  • 嗯似乎不起作用,我的 IF 语句的位置是否正确?
  • @user2863681 抱歉,我忘记为 FileOutputStream 设置“附加”标志。否则,文件将始终被覆盖。现在它应该在每次创建流时附加。
  • 请注意,最好在开始时只打开一次流。因此,您可以在循环之前移动 try(...) 语句并在之后移动结束括号。
  • 啊,好吧,似乎只是将商店“单元一”输出到文件中,它也没有对单元 2-9 进行计算?
  • @user2863681 看看我的小改动:现在用第二个参数 (true) 创建 FileOutputStream。这将启用附加(默认值:false = 覆盖现有文件)。
猜你喜欢
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 2016-07-13
相关资源
最近更新 更多