【问题标题】:Finding an index of an array, then finding the value based off that index查找数组的索引,然后根据该索引查找值
【发布时间】:2019-11-12 14:52:44
【问题描述】:

我正在尝试使用表示数组索引的 i 值在列表中递增,然后我需要根据该索引找到值。

我尝试将我要查找的值指定为 -2,然后在列表中递增以找到索引。但我不完全确定如何从索引中获取实际值。 studentId 不是我打算返回的,但是当我尝试返回时它说的是它必须是一个整数。有人可以向我展示如何通过列表索引成功获取值吗?

public int studentfinder( int list[]  ,  int studentId  )
{ 
    int correct = -2; 
    for (int i = 0;i<array.length;i++)
    {
        if (list[i] == correct)
        {
            return studentId;
        }
        else
        {
            studentId = -1;
            return studentId;
        }
    }
}

该方法必须返回int类型的结果

【问题讨论】:

    标签: java arrays indexing processing


    【解决方案1】:

    检查以下代码

    public int studentfinder( int list[]  ,  int studentId  ) {
        for (int i = 0;i<list.length;i++) {
            if (list[i] == studentId) {
                return studentId;
            }
        }
        return -1;
    }
    

    array.length 不会在您的代码中编译,因为没有具有数组名称的对象。

    让我们假设 studentId 是 int list[] 数组中的一个 int。

    您执行一个 for 循环,直到找到 list[i]==studentId,找到后该方法返回该 studentId。

    如果 for 循环在没有找到 studentId 的情况下退出,则返回 -1,表示在列表中没有找到 studentId(同时假设 studentIds 不是负整数)。

    【讨论】:

    • 您好 Joel,此方法不应在 Java 中产生任何编译或语法错误。列表数组在方法签名(在参数中)定义为 int list[]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2018-04-20
    • 2019-03-18
    相关资源
    最近更新 更多