gpt4 book ai didi

java - 查找数组的索引,然后根据该索引查找值

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

我尝试使用 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 类型的结果

最佳答案

检查以下代码

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不是负整数)。

关于java - 查找数组的索引,然后根据该索引查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58821140/

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