【问题标题】:Write search methods in array by Java用Java在数组中编写搜索方法
【发布时间】:2017-03-16 21:20:11
【问题描述】:

我有一个数组(id,name,salary) 我想使用员工搜索方法搜索特定的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;
}

【问题讨论】:

  • 那么,有什么问题?
  • 我看不出是什么问题。
  • 我有错误,无法完成
  • 您是否有编译器错误或运行时错误?什么错误信息?
  • 如果您有错误,那么您至少可以告诉我们错误是什么。

标签: java arrays search


【解决方案1】:

您的 SearchID 方法返回一个 Employee 对象,但您返回一个原始类型。 (staff[i].id) 您必须更改方法的返回类型。

【讨论】:

  • 如何更改类型?
  • 这取决于您是否真的想返回员工并且需要更改返回类型,或者您是否真的想返回 ID 并且需要更改方法签名?
【解决方案2】:

你可以像这样修复你的方法:

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;
}

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

【讨论】:

  • 您可以删除 check 变量,因为它从未使用过。
猜你喜欢
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
相关资源
最近更新 更多