我在這個(我的第一個)學期結束時遇到了我的程序的特定部分問題。所以我必須帶一個文本文件,其中包括姓名和一些數字,並對每個人的數字進行一些計算。我試圖用循環創建一個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