亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

java中的數組里面的數組

java中的數組里面的數組

神不在的星期二 2022-05-21 16:53:24
我想通過訪問父數組來制作多個數組。例如。如何制作這個數組?在這里,在這段代碼中,用戶輸入了以下數據,代碼將簡單地打印數組,即 2-> 父數組的總大?。ㄋ鼤嬖V編譯器用戶將輸入兩個數組作為輸入) 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 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號