我在这个(我的第一个)学期结束时遇到了我的程序的特定部分问题。所以我必须带一个文本文件,其中包括姓名和一些数字,并对每个人的数字进行一些计算。我试图用循环创建一个2维数组,并将数字(保存为字符串)转换为双精度数组。问题在于,我不能将j = 3
和j = 4
的值用于计算,因为这是分配的另一半。从文本文件中创建二维数组
所以我需要一种方法来将j = 0
和1的值存储为字符串,并将j = 2,3和4的值作为双精度来存储 - 如果可能的话,最好在相同的数组中。
我的教授(谁没有多少记住)说了一些关于使用多种方法。如果你看看下面几行:
double empPay = empHoursResult * empRateResult;
System.out.println(arr[3] * arr[4]);
无论这些工作,因为我要么需要初始化双打(这使它们= 0)和arr[j]
值存储为字符串。
如何将j > 1
的值存储为双打,而j = 0,1作为字符串?任何建议表示赞赏。谢谢。
public static void main(String[] args) {
String[] textLine = new String[10];
int i = 0;
String empNumber;
String empHours;
String empRate;
double empNumberResult;
double empHoursResult;
double empRateResult;
System.out.println("Reading File ......");
String fileName = "datatext.txt";
try {
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
while ((line = bufferReader.readLine()) != null) {
textLine[i] = line;
i++;
}
for (int x = 0; x < i; x++) { //For loop of the rows, each employee.
String empInfo = textLine[x];
String[] arr = empInfo.split(" ");
System.out.println("\nEmployee: " + (x + 1));
for (int j = 0; j < arr.length; j++) {
if (j == 0) {
System.out.println("Last Name: " + arr[j]);
} else if (j == 1) {
System.out.println("First Name: " + arr[j]);
} else if (j == 2) {
empNumber = arr[j];
empNumberResult = Double.parseDouble(empNumber);
System.out.println("Employee Number: " + empNumberResult);
} else if (j == 3) {
empHours = arr[j];
empHoursResult = Double.parseDouble(empHours);
System.out.println("Total Hours Worked: " + empHoursResult);
} else if (j == 4) {
empRate = arr[j];
empRateResult = Double.parseDouble(empRate);
System.out.println("Employee Hourly Rate: " + empRateResult); // Read above line ^^.
}
}
double empPay = empHoursResult * empRateResult;
System.out.println(arr[3] * arr[4]);
/*
* Here is where I want the system to print out calculations from below.
* The calculatePay method must be somewhere in the first 'for loop' because I need it
* to calculate pay for all employess, x.
*/
}
bufferReader.close();
} catch (Exception e) {
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
public static void calculatePay(double empHoursResult, double empRateResult) {
double empNormalPay;
double empOvertimePay;
double empOvertimeHours;
double empTotalPay;
if (empHoursResult > 40) {
empNormalPay = 40 * empRateResult;
empOvertimeHours = 40 - empHoursResult;
empOvertimePay = empOvertimeHours * 1.5;
empTotalPay = empNormalPay = empOvertimePay;
}
}
您确定要将字符串和双打存储在同一个数组中吗?也许你应该为每个员工创建一个对象并将这些对象存储在一个数组中。顺便说一句。你的内循环是不需要的。只要执行'empNumber = arr [2];'等 – SpiderPig