•创建工资单文件
•工资单文件包含两个部门,人力资源和警察部门的20名员工的每小时工资信息。该文件将有两列浮点数。第一栏是人力资源,第二栏是警察局。所以每行有两个浮点数。
•您需要使用[0,100]中的随机数作为双精度类型创建工资核算文件。
•阅读工资单文件。
•您需要使用Scanner对象的nextLine()来读取工资单文件中的每一行。
•通过使用我们在课堂上讨论过的splitString()函数,解析每一行以获得两小时支付的数组。该函数将返回String []类型。 String和Character类的功能将有助于解决splitString。
•计算每个部门的总工资和平均工资
•您需要使用Double.parseDouble()将String类型的pay转换为double类型
•写一个包含总工资和平均工资的输出文件。
•输入文件名使用“pay.txt”,输出文件名使用“summary.txt”。
现在我明白了如何在没有数组的情况下做到这一点,因为我已经完成了。但是一旦我将txt文件解析成多个数组,我就完全迷失了。我的教授禁止我们使用in.hasNextDouble(),这就是我解决最后一个程序的方法。如何将程序中txt文件中同一行的两个数字分成两个不同的数组呢?
以下是上一个程序的代码,以及我目前使用当前程序的代码。
public class FileHandling {
public static void main(String [] args) throws FileNotFoundException{
File inputFileName = new File("input.txt");
Scanner in = new Scanner(inputFileName);
double averageWorker = 0;
double averageHr = 0;
double totalWorkerPay = 0;
System.out.println(" HR\t\tWorkers");
double totalHrPay = 0;
while (in.hasNextDouble()) {
double humanResourcesPay = in.nextDouble();
System.out.printf("%8.3f\t", humanResourcesPay);
totalHrPay += humanResourcesPay;
double workerPay = in.nextDouble();
System.out.printf("%.3f\n", workerPay);
totalWorkerPay += workerPay;
averageWorker = totalWorkerPay/3;
averageHr = totalHrPay/3;
}
System.out.printf("Total pay for HR is %.1f", totalHrPay);
System.out.printf("\nAverage pay for HR is %.1f", averageHr);
System.out.printf("\nThe total pay for Workers is %.1f", totalWorkerPay);
System.out.printf("\nAverage pay for Workers is %.1f", averageWorker);
System.out.print("\nEnter the file name:");
Scanner console = new Scanner(System.in);
String outputFileName = console.nextLine();
PrintWriter out = new PrintWriter(outputFileName);
System.out.println("total is " + totalHrPay);
in.close();
out.close();
}
}
好的,这是我到目前为止在这个作业上的内容。
public class FileHandlingNextLine {
public static void main(String [] args) throws FileNotFoundException{
File inputFileName = new File("pay.txt");
Scanner in = new Scanner(inputFileName);
int i = 0;
int j = 0;
double total[] = new double[2];
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println("Line : " + line);
String pays[] = splitString(line);
for(i = 0; i < pays.length; i++) {
System.out.printf(pays[i]);
total[i] += Double.parseDouble(pays[i]);
}
}
}
任何帮助都会受到赞赏,我很遗憾,我的老师也没什么帮助。