Java 输出写入屏幕,然后写入输出文件?
基本上,我必须从输入文件中读取一些数据,并进行一些计算,以计算每个单位的总员工成本,下面的输入格式如下所示Java 输出写入屏幕,然后写入输出文件?,java,loops,if-statement,console,output,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 我缩短了我的代码,因为它有很多else-if语句,什么设计模式适合删除许多if和else或e
<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
我缩短了我的代码,因为它有很多else-if语句,什么设计模式适合删除许多if和else或else-if语句?不要委托
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");
}
你能格式化你的代码使其更可读吗?你的意思是如何使其更可读?编辑你的问题并使用适当的制表符/间距。Uhmm似乎不起作用,我的IF语句的位置是否正确?@user2863681对不起,我忘了为FileOutputStream设置“append”标志。如果没有,文件将始终被覆盖。现在,它应该在每次创建流时追加。请注意,最好在开始时只打开一次流。因此,您可以在循环之前移动try(…)语句,然后移动结束括号。啊,好吧,似乎只是将shop“unit one”输出输入到文件中,它也没有对unit 2-9进行计算?@user2863681查看我的小改动:现在使用第二个参数(true)创建FileOutputStream。这将启用追加(默认值:false=覆盖现有文件)。
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");
}