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

使用循环填充多维数组(NetBeans IDE 8.2):实现两个2×2数组填充

解决2×2数组填充的完整逻辑

嘿,我来帮你搞定这两个数组的填充问题!首先得提醒你一个关键细节:Java里数组的索引是从0开始的,你原来的循环从1开始会触发数组越界异常哦,咱们先把这个问题修正,再补全填充逻辑。

完整代码实现

下面是补全后的可运行代码,我会一步步拆解每个部分的作用:

package javaapplication24;
import java.util.Scanner;

public class JavaApplication24 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        // 直接初始化两个2×2数组(简化你原来的分步写法)
        String[][] arrString = new String[2][2];
        int[][] arrInt = new int[2][2];
        
        // 填充String类型数组
        System.out.println("=== 开始填充String数组 ===");
        for(int row = 0; row < 2; row++){ // 遍历行,索引从0到1(共2行)
            for(int col = 0; col < 2; col++){ // 遍历列,索引从0到1(共2列)
                // 给用户的提示用row+1/col+1,符合日常“第1行第1列”的认知
                System.out.printf("请输入第%d行第%d列的字符串:", row+1, col+1);
                arrString[row][col] = sc.nextLine(); // 将输入值赋值给对应数组位置
            }
        }
        
        // 处理int输入前的换行符残留:nextInt()不会读取换行符,这里清空避免跳过输入
        sc.nextLine();
        
        // 填充int类型数组
        System.out.println("\n=== 开始填充int数组 ===");
        for(int row = 0; row < 2; row++){
            for(int col = 0; col < 2; col++){
                System.out.printf("请输入第%d行第%d列的整数:", row+1, col+1);
                // 简单读取整数,若要更严谨可以加异常捕获(比如处理非整数输入)
                arrInt[row][col] = sc.nextInt();
            }
        }
        
        // 可选:打印数组内容,验证填充结果
        System.out.println("\n=== 已填充的String数组 ===");
        for(String[] row : arrString){
            for(String str : row){
                System.out.print(str + "\t");
            }
            System.out.println();
        }
        
        System.out.println("\n=== 已填充的int数组 ===");
        for(int[] row : arrInt){
            for(int num : row){
                System.out.print(num + "\t");
            }
            System.out.println();
        }
        
        sc.close(); // 关闭Scanner资源,避免内存泄漏
    }
}

核心细节解释

  • 循环逻辑修正:把循环起始值改成0,用row < 2作为终止条件,比a != 3更安全——后者如果循环变量意外被修改,会导致死循环。
  • String输入处理:用sc.nextLine()可以读取包含空格的完整字符串,比sc.next()更灵活。
  • int输入的坑:sc.nextInt()只会读取整数部分,输入后残留的换行符会被下一次nextLine()直接读取,所以在填充int数组前加了sc.nextLine()清空输入流。
  • 验证输出:最后添加的遍历打印代码,能让你直观看到数组是否被正确填充,方便调试。

运行效果

启动程序后,会依次引导你输入4个字符串和4个整数,最后自动输出两个数组的内容,完全满足你的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:59:48