You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组指定索引元素打印问题:代码无法输出目标索引对应值

修正代码以获取指定索引的元素

你的代码逻辑和需求完全相反:当前findElementAtIndex方法的作用是查找值等于key的元素的索引,但你需要的是根据索引key获取对应位置的元素值,这就是你无法得到预期结果的原因。

Java中数组可以直接通过arr[索引]访问指定位置的元素,根本不需要循环遍历。下面是两种修正方案:

方案一:修改方法逻辑实现需求

public class PresentIndex {
    // 方法功能改为:传入索引key,返回对应位置的元素
    public static int findElementAtIndex(int arr[], int key){
        // 先判断索引是否合法,避免数组越界异常
        if (key >= 0 && key < arr.length) {
            return arr[key];
        }
        // 索引不合法时返回标识值(可根据需求调整)
        return -1;
    }

    public static void main(String[] args) {
        int arr[] = {10, 20, 30, 40, 50};
        int key = 2;
        int element = findElementAtIndex(arr, key);
        if (element != -1) {
            System.out.println("索引" + key + "对应的元素是:" + element);
        } else {
            System.out.println("输入的索引不合法");
        }
    }
}

方案二:直接在main方法中访问(更简洁)

如果不需要单独封装方法,直接在main里处理更高效:

public class PresentIndex {
    public static void main(String[] args) {
        int arr[] = {10, 20, 30, 40, 50};
        int key = 2;
        // 索引合法性检查
        if (key >= 0 && key < arr.length) {
            System.out.println("索引" + key + "对应的元素是:" + arr[key]);
        } else {
            System.out.println("索引超出数组范围,请检查输入");
        }
    }
}

说明

  • 数组索引从0开始,所以key=2对应数组中的第3个元素30,修正后的代码会正确输出这个值。
  • 添加索引合法性判断是为了防止出现ArrayIndexOutOfBoundsException,当输入的key小于0或者大于等于数组长度时,会给出明确提示。

内容的提问来源于stack exchange,提问作者Sunitha Reddy Gudisela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:12:25