[英]Java - Read and search CSV file and display results
我正在編寫一個程序來顯示從 CSV 文件中讀取的員工列表。 然后我希望能夠根據 ID 號選擇一名員工並顯示有關他們的信息。 用戶將輸入員工 ID 號並搜索 CSV 文件以顯示該員工信息。
注意:我不想使用 CSV 庫,因為我仍在學習基礎知識。
CSV 文件內容是:(標題不在文件中,只是為了了解信息)
EmpID,Name,Age,Position,Type,Rate
1,Jason Thomas-Junior,27,Sales,Full Time,150
2,Tim Green,25,Sales,Full Time,59
3,Tony Watson,25,Sales,Casual,55
4,Geoff Hart,27,Sales,Casual,110
5,Fred Mercury,35,Supervisor,Full Time,60
我能夠以以下格式顯示信息:
____________________________________________________________________
EmpID Name Age Position Type Rate/Day
1 Jason Thomas-Junior 27 Sales Full Time 150.0
2 Tim Green 25 Sales Full Time 59.0
3 Tony Watson 25 Sales Caual 55.0
4 Geoff Hart 27 Sales Casual 110.0
5 Fred Mercury 35 Supervisor Full Time 60.0
____________________________________________________________________
我顯示上面輸出的代碼是:
try {
Scanner fileScanner = new Scanner(new FileReader("EmpList.csv"));
fileScanner.useDelimiter(",");
while (fileScanner.hasNextLine()) {
fileName = fileScanner.nextLine();
String[] data = fileName.split(",");
int empID = Integer.parseInt(data[0]);
String empName = data[1];
int empAge= Integer.parseInt(data[2]);
String empPosition = data[3];
String empType = data[4];
double empRate= Double.parseDouble(data[5]);
System.out.printf("%-9s%-16s%-8s%-14s%-10s%-8s\n"
, empID , empName , empAge, empPosition , empType , empRate);
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
我現在被困在如何搜索 EmpID 並以以下格式顯示匯總結果:
System.out.println("Select the employee number from the list: ");
Employee is: name
Employees rate is: rate
任何幫助是極大的贊賞。
首先創建一個 Employee 類,然后創建實例變量 ID、名稱、年齡、職位、類型、比率,並創建 setter 和 getter 方法。
之后在上面的代碼中創建像這樣的員工類對象的arraylist實例。
ArrayList<Employee> employee = new ArrayList<>();
現在在您的 while 循環中將新員工詳細信息添加到您的列表對象中。
employee.add(new Employee(X,XX,XX,XX,XX));
一旦您從文件中讀取所有記錄,您就可以對其執行搜索功能。
對於搜索,您可以對列表進行迭代。
//for validation
boolean flag = false;
for(Employee emp:employee){
if(emp.getID() == 101){
//enter print code here
flag = true;
}
}
if(!flag) //print no record found
您應該為此使用哈希表或任何其他類似的類。 創建一個名為employee 的類。
Class Employee
{
//declare employee fields on here
}
//declare hash table to input employee details
Hashtable<Integer,Employee> EmployeeTable=new Hashtable<Integer,Employee>();
//accept input as employee object in your while loop
while (fileScanner.hasNextLine()) {
fileName = fileScanner.nextLine();
String[] data = fileName.split(",");
Employee obj=new Employee()//
//write code to input values to employee
EmployeeTable.put(obj.ID,obj); //put employee id as key and employee as data
}
/* 使用員工 ID 鍵獲取值 */ EmployeeTable.get(employee_id);//
請參閱https://www.geeksforgeeks.org/hashtable-get-method-in-java/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.