2014-02-16 61 views
0

鑑於我目前的代碼,我怎樣才能以矩陣格式輸出它?我目前的輸出方法只是直線列出數組。不過,我需要將它們堆疊在相應的輸入參數中,以便3x3輸入生成3x3輸出。謝謝!作爲矩陣打印自定義2d陣列

import java.util.Scanner; 

回答

0
for (int i =0; i < rows; i++) { 
    for (int j = 0; j < columns ; j++) { 
     System.out.print(" " + array2d[i][j]); 
    } 
    System.out.println(""); 
} 
1
for(int row = 0; row < rows; row++){ 
    for(int column = 0; column < columns; column++){ 
     System.out.print(array2d[row][column] + " "); 
    } 
    System.out.println(); 
} 

這將打印出一行一行的,然後移動到下一行,並打印出它的內容,等等,您所提供和作品的代碼進行測試。

編輯 - 增加了代碼,你想要的方式:

public static void main(String[] args) { 

    Scanner scan =new Scanner(System.in); //creates scanner object 

    System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array 
    int rows = scan.nextInt(); //takes input for response 

    System.out.println("How many columns to fill?"); 
    int columns = scan.nextInt(); 
    int[][] array2d=new int[rows][columns]; //array for the elements 

    for(int row=0;row<rows;row++) 
     for (int column=0; column < columns; column++) 
     { 
     System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input 
     array2d[row][column]=scan.nextInt(); //Takes in current input 
     } 

    System.out.println(Arrays.deepToString(array2d)); 

    String[][] split = new String[1][rows]; 

    split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], [")); //split at the comma 

    for(int row = 0; row < rows; row++){ 
     System.out.println(split[0][row]); 
    } 

    scan.close(); 
} 
+0

大謝謝!有沒有辦法用我最初使用的Array.DeeptoString方法做到這一點?只是好奇,我實際上並不需要 – user3294617

+0

絕對是!將'Arrays.deepToString(array2d)'拆分爲''',並將它們放入另一個數組,其大小基於'array2d [] []'的行數。然後使用相同的循環邏輯打印出來。讓我知道你是否願意幫忙。接受我的答案,如果它幫助你了! –

+0

好吧,我想通了(雖然目前看起來很糟糕,你可以自己計算格式);)。它需要'Arrays.deepToString(array2d)'並分割和輸出。您感興趣的行是'split [0] =(Arrays.deepToString(array2d))。split(Pattern.quote(「],[」));'。 –