如何在Java中通过Scanner输入创建指定结构的二维数组
正确实现Java Scanner输入创建指定二维数组的方法
你的问题在于使用了固定大小的二维数组,但输入内容并非每行都有2个数字,且期望的结果是子数组长度不同的不规则二维数组,固定长度数组无法满足需求。以下是正确的实现方式:
实现思路
- 先用
Scanner读取第一行的两个整数,组成第一个长度为2的子数组 - 依次读取后续每行的单个整数,每个整数单独作为一个长度为1的子数组
- 使用
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
相关产品推荐
相关产品推荐

