为了账号安全,请及时绑定邮箱和手机立即绑定

java中的数组里面的数组

java中的数组里面的数组

神不在的星期二 2022-05-21 16:53:24
我想通过访问父数组来制作多个数组。例如。如何制作这个数组?在这里,在这段代码中,用户输入了以下数据,代码将简单地打印数组,即 2-> 父数组的总大小(它会告诉编译器用户将输入两个数组作为输入) 6->第一个子数组的大小等等。265 1 3 4 18 5688 7 3 1 34 72 89 11并且它们都是用户输入的,甚至是数组的大小。 public static void main(String[] args) {   Scanner sc = new Scanner(System.in);   int sarr[] = new int[30];   int arr[] =  new int[30];   int n =sc.nextInt();   for (int i=0;i<n;i++)   { sarr[i] = sc.nextInt();     for (int j=0;j<=sarr[i];j++)     {       arr[j]=sc.nextInt();     }   }   for (int i=0;i<n;i++)   {      for (int j=0;j<=sarr[i];j++)     {         System.out.println(arr[i]);     }     System.out.println();   }
查看完整描述

2 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

如果你想在java中创建一个多维数组,你应该使用这个语法:


int n = ...; 

int array[][] = new int[n][n];

例如:


try (Scanner sc = new Scanner(System.in)) {

        int n = sc.nextInt();

        int arr[][] = new int[n][n];

        for (int i = 0; i < n; i++) {

            for (int j = 0; j < n; j++) {

                arr[i][j] = sc.nextInt();

            }

        }

        for (int i = 0; i < n; i++) {

            for (int j = 0; j < n; j++) {

                System.out.println(arr[i][j]);

            }

            System.out.println();

        }

    }

一些最后的笔记:


完成后应该关闭流

您不会“告诉编译器”,因为编译器不会在运行时执行。无论如何,您的意思是JVM。


查看完整回答
反对 回复 2022-05-21
?
噜噜哒

TA贡献1784条经验 获得超7个赞

这是一个关于如何构建具有不同大小行的二维数组的解决方案。每个数组都是在我们询问其大小后创建的


Scanner sc = new Scanner(System.in);

System.out.println("Number of arrays");

String str1 = sc.nextLine();

int numberOfArrays = Integer.valueOf(str1);


int[][] array = new int[numberOfArrays][];


    for (int i = 0; i < numberOfArrays; i++) {

        System.out.println("Size of array");

        String str2 = sc.nextLine();

        int size = Integer.valueOf(str2);

        int[] row = new int[size];

        for (int j = 0; j < size; j++) {

            System.out.println("Value:");

            String str3 = sc.nextLine();

            int value = Integer.valueOf(str3);

            row[j] = value;

        }

        array[i] = row;        

    }

}

更新


这是一个允许在一行中输入数组中的所有数字的版本。请注意,这里没有错误处理检查给定值与预期值的数量等。


for (int i = 0; i < numberOfArrays; i++) {

    System.out.println("Size of array");

    String str2 = sc.nextLine();

    int size = Integer.valueOf(str2);

    int[] row = new int[size];

    System.out.println("Values:");

    String str3 = sc.nextLine();

    String[] numbers = str3.split("\\s");

    for (int j = 0; j < size; j++) {

        row[j] = Integer.valueOf(numbers[j]);

    }

    array[i] = row;

}


查看完整回答
反对 回复 2022-05-21
  • 2 回答
  • 0 关注
  • 210 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号