【发布时间】:2016-12-10 18:18:12
【问题描述】:
我在这个(我的第一个)学期末的课程的特定部分遇到了问题。所以我必须获取一个文本文件,其中包括姓名和一些数字,并对每个人的数字进行一些计算。我试图用循环创建一个二维数组,并将数字(保存为字符串)转换为双精度数。问题是我不能使用 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;
}
}
【问题讨论】:
-
您确定要将字符串和双精度值存储在同一个数组中吗?也许您应该为每个员工创建一个对象并将这些对象存储在一个数组中。顺便提一句。不需要您的内部 for 循环。只要做
empNumber = arr[2];等。
标签: java arrays string numbers