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

如何在Java中通过Scanner输入创建指定结构的二维数组

正确实现Java Scanner输入创建指定二维数组的方法

你的问题在于使用了固定大小的二维数组,但输入内容并非每行都有2个数字,且期望的结果是子数组长度不同的不规则二维数组,固定长度数组无法满足需求。以下是正确的实现方式:

实现思路

  1. 先用Scanner读取第一行的两个整数,组成第一个长度为2的子数组
  2. 依次读取后续每行的单个整数,每个整数单独作为一个长度为1的子数组
  3. 使用ArrayList<int[]>动态存储这些子数组,最后转换为二维数组

完整代码

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<int[]> subArrays = new ArrayList<>();
        
        // 读取第一行的两个数字,构造第一个子数组
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        subArrays.add(new int[]{num1, num2});
        
        // 读取剩余所有整数,每个单独作为子数组
        while (sc.hasNextInt()) {
            int num = sc.nextInt();
            subArrays.add(new int[]{num});
        }
        
        // 转换为二维数组
        int[][] nodes = subArrays.toArray(new int[subArrays.size()][]);
        
        // 验证输出(可选)
        System.out.print("[");
        for (int i = 0; i < nodes.length; i++) {
            System.out.print("[");
            for (int j = 0; j < nodes[i].length; j++) {
                System.out.print(nodes[i][j]);
                if (j != nodes[i].length - 1) {
                    System.out.print(",");
                }
            }
            System.out.print("]");
            if (i != nodes.length - 1) {
                System.out.print(",");
            }
        }
        System.out.print("]"); // 最终输出:[[1,2],[3],[3],[-1]]
        
        sc.close();
    }
}

原代码问题说明

  • 你定义的int nodes[][] = new int[4][2];是固定4行2列的数组,当输入后续每行只有1个数字时,内层循环会等待读取第二个数字,导致程序卡住或读取错误
  • 固定长度数组无法生成子数组长度不同的不规则二维数组,而ArrayList可以灵活添加任意长度的子数组

内容的提问来源于stack exchange,提问作者Pyae Phyoe Shein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:01:46