在我的程序中,我扫描了2个文件,第一个文件我得到了小时数,而payRate用于计算每个员工的基本工资,第二个文件得到每个员工的销售额以计算该周的佣金。
然后我将结果合并到一个文件中,但我需要为每位员工添加佣金和基本工资,以获得每位员工的每周支付。我迷失在这里,我想用各自的佣金添加每个基本工资以获得每周的支付,同时,我添加了社会安全号码,有没有办法我可以用单独的文件或者同一文件扫描具有相同标识符的数字(在这种情况下是相同的社会安全号码)并添加相应的值?Two files (1) Salary_Hours (2) Sales
import java.util.*;
import java.io.*;
public class Payroll_Sales {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) throws IOException {
File fileSalary = new File ("Salary.txt");
File salaryFile = new File ("NewPrint.txt");
PrintWriter salaryPrint = new PrintWriter (salaryFile);
salaryPrint = getSalary (fileSalary, salaryFile);
File fileSales = new File ("Sales.txt");
FileWriter salesFile = new FileWriter ("NewPrint.txt", true);
PrintWriter salesPrint = new PrintWriter (salesFile);
salesPrint = getSales (fileSales, salesFile);
}
private static PrintWriter getSales(File fileSales, FileWriter salesFile) throws FileNotFoundException {
PrintWriter salesPrint = new PrintWriter (salesFile);
Scanner scan = new Scanner (fileSales);
String ssn;
double sales = 0, commission=0, salesCommission=0;
while (scan.hasNext()) {
ssn = scan.next();
sales = scan.nextDouble();
if (sales >= 10000) {
commission = .15;
}
else if (sales >= 7500) {
commission = .10;
}
else if (sales >= 4500) {
commission = .07;
}
else {
commission = .05;
}
salesCommission = commission*sales;
salesPrint.printf("%11s $ %,3.2f \n", ssn, salesCommission);
System.out.printf("%11s $ %,3.2f \n", ssn, salesCommission);
}
salesPrint.close();
return salesPrint;
}
private static PrintWriter getSalary(File fileSalary, File salaryFile) throws FileNotFoundException {
PrintWriter salaryPrint = new PrintWriter (salaryFile);
Scanner scan = new Scanner (fileSalary);
String ssn;
double salary = 0, hours=0, payRate=0;
while (scan.hasNext()) {
ssn = scan.next();
payRate = scan.nextDouble();
hours = scan.nextDouble();
salary = payRate * hours;
salaryPrint.printf("%11s $ %,3.2f \n", ssn, salary);
System.out.printf("%11s $ %,3.2f \n", ssn, salary);
}
System.out.println();
salaryPrint.println();
salaryPrint.close();
return salaryPrint;
}
}
答案 0 :(得分:0)
根据我的经验,我倾向于将文件或IO工作分为两个步骤。
1)将输入解析为模型
这可以是一个代表您的应用程序的类,其中包含不同数据类型的其他类(员工有销售数量,支付率,数小时等)
2)现在你已经拥有了你的模型,介绍了你的业务逻辑,因为你应该拥有自解析完成以来所需的所有信息。
请注意,根据输入的大小,所需的内存量将按比例缩放,因此如果这些文件的大小非常大,我建议您引入数据库或其他更容易管理的内容( 我不希望根据您的初始代码确定这是必要的)
pseduo代码看起来像这样
public static <ModelClass> parseInput(file1, file2){
//Read through the files and instantiate your model data
//This should cover any information you need in your business logic
//(Meaning you should be able to close the files and not open them again
}
public <ModelClass> calculatePay(<ModelClass> model){
//Use your data structure to compute what you want to compute
//Return modified instance of the model
}
我建议的原因是因为我过去花了太多时间尝试一次性完成所有操作(从文件和计算逻辑中解析数据)。它并不总是正确的答案,但这就是重构的目的!