gpt4 book ai didi

java - 如何在 Java 中编写增强型 for 循环

转载 作者:行者123 更新时间:2023-12-01 17:44:16 24 4
gpt4 key购买 nike

我正在尝试写这个for loop使用enhanced for loop但它给了我错误 类型 ArrayList 中的方法 get(int) 不适用于参数 (Employee)

我知道这是因为 ArrayLists 方法的 get()需要Integer type 数据类型作为参数,但我需要将其转换为增强的 for 循环。这是我到目前为止所尝试过的。

这是原始代码 traditional for loop

//display employees
public void outputEmployee(ArrayList<Employee> list) {

System.out.println("Employee ID" + "\t\t" + "Full Name" + "\t\t" + "Address" + "\t\t" + "Faculty Name" + "\t\t"
+ "Department" + "\t\t" + "Designation" + "\n");
System.out.println(
"================================================================================================================");

for (int i = 0; i < list.size(); i++) {
Employee employee = list.get(i);
System.out.println(employee.getEmployeeId() + "\t" + employee.getEmployeeFullName() + "\t\t" + employee.getEmployeeAddress() + "\t"
+ employee.getFacultyName() + "\t" + employee.getDepartment() + "\t" + employee.getEmployeeDesignation() + "\n");
System.out.println(
"----------------------------------------------------------------------------------------------------------------");
}

}

这是我尝试过的:

//display employees
public void outputEmployee(ArrayList<Employee> list) {

System.out.println("Employee ID" + "\t\t" + "Full Name" + "\t\t" + "Address" + "\t\t" + "Faculty Name" + "\t\t"
+ "Department" + "\t\t" + "Designation" + "\n");
System.out.println(
"================================================================================================================");

for(Employee emp : list) {
Employee employee = list.get(emp); //gives error here
System.out.println(employee.getEmployeeId() + "\t" + employee.getEmployeeFullName() + "\t\t" + employee.getEmployeeAddress() + "\t"
+ employee.getFacultyName() + "\t" + employee.getDepartment() + "\t" + employee.getEmployeeDesignation() + "\n");
System.out.println(
"----------------------------------------------------------------------------------------------------------------");
}

}

有人可以帮我吗?

最佳答案

这里:

for(Employee emp : list) {
Employee employee = list.get(emp); //gives error here

根本不需要第二行。您已经迭代列表中的成员。 emp 变量/引用指向该列表的成员。

那你就走吧

System.out.println(emp.getEmployeeId() ...

或者,将循环更改为

for(Employee employee : list) { ...

这就是全部内容了。

关于java - 如何在 Java 中编写增强型 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com