用Java编写数组中的搜索方法

用Java编写数组中的搜索方法,java,arrays,search,Java,Arrays,Search,我有一个数组,它有(id、姓名、薪水) 我想使用员工搜索方法搜索特定的ID,我的代码是: Employee SearchID(int i_d) { for (int i = 0; i < staff.length; i++) { boolean check = true; if (staff[i].id == i_d) { System.out.println("Id: " + staff[i].id + ", name: "

我有一个数组,它有
(id、姓名、薪水)
我想使用员工搜索方法搜索特定的
ID
,我的代码是:

Employee SearchID(int i_d) {
    for (int i = 0; i < staff.length; i++) {
        boolean check = true;
        if (staff[i].id == i_d) {
            System.out.println("Id: " + staff[i].id + ", name: " + staff[i].name + " and salary: " + staff[i].salary);
        } else {
            System.out.println("Sorry, no record exists with record id = " + i_d);
        }
    }
 return staff[i].id;
}
Employee SearchID(内部ID){
对于(int i=0;i
您的SearchID方法返回一个Employee对象,但您返回一个基元类型。(staff[i].id)必须更改方法的返回类型

您可以这样修复您的方法:

Employee SearchID(int i_d) {
    for (int i = 0; i < staff.length; i++) {
        if (staff[i].id == i_d) {
            System.out.println("Id: " + staff[i].id + ", name: " + staff[i].name + " and salary: " + staff[i].salary);
            return staff[i];
        }
    }
    System.out.println("Sorry, no record exists with record id = " + i_d);
    return null;
}
Employee SearchID(内部ID){
对于(int i=0;i

当然,在调用
SearchID
之后,您需要正确处理
null
结果。

那么,问题出在哪里?我不知道问题出在哪里。我有错误,无法完成。您有编译器错误还是运行时错误?什么错误消息?如果您有错误,那么您至少可以告诉我们错误是什么。我如何更改类型?这将取决于您是否确实希望返回员工并需要更改返回类型,还是确实希望返回ID并需要更改方法签名?您可以删除
检查变量,因为它从未使用过。