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

Java实现创建指定大小数组填充1~n值并按索引打印元素

代码修改方案

现有代码存在的问题

  • 没有实现数组填充逻辑:创建数组后未赋值,元素默认都是0,无法得到1到数组长度的数值
  • 数组访问越界:循环中使用arr[i]取值,i是数组的总长度,而数组最大合法索引为i-1,运行会直接抛出ArrayIndexOutOfBoundsException异常
  • 输出格式错误:代码尝试先输出元素值再输出冒号,和要求的「索引: 元素值」顺序相反,也没有对应输出元素值的逻辑

修改后完整代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("How large an array? ");
        int arrayLength = sc.nextInt();
        int[] arr = new int[arrayLength];
        
        // 填充数组+打印合并实现,也可以拆分两个循环单独处理
        for (int index = 0; index < arrayLength; index++) {
            arr[index] = index + 1;
            System.out.println(index + ": " + arr[index]);
        }
        
        sc.close();
    }
}

运行验证

输入5时,输出结果为:

0: 1
1: 2
2: 3
3: 4
4: 5

完全符合要求的输出效果。

内容的提问来源于stack exchange,提问作者swu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:15:06