2014-01-06 44 views
2

我想打印inputed 2維數組如表 即如果由於某種原因,他們把所有秒...打印在Java中的二維數組一樣的表

1 1 1 1 

1 1 1 1 

1 1 1 1 

1 1 1 1 

就像所以以上,但在日食的Java控制檯,沒有華麗的按鈕和GUI的,但在控制檯中,這裏是我....

import java.util.Scanner; 
    public class Client { 
     public static void main(String[] args){ 
      Scanner input = new Scanner(System.in); 

      int[][] table = new int[4][4]; 
      for (int i=0; i < table.length; i++) { 
       for (int j=0; j < table.length; j++) { 
        System.out.println("Enter a number."); 
        int x = input.nextInt(); 
        table[i][j] = x; 
        System.out.print(table[i][j] + " "); 
       } 
        System.out.println(); 
     } 
     System.out.println(table); 
    } 
} 

這是我所得到的,當我輸入的一切,控制檯終止:

Enter a number. 

1 

1 Enter a number. 

1 

1 Enter a number. 

1 

1 Enter a number. 

1 

1 

[[[email protected] 
+0

我反對票是有原因的,如:「缺乏研究」。 –

+0

對不起,但我找不到這個地方,如果你可以告訴我一個問題,問如何在控制檯中打印數組,那麼我不會問你的downvote –

+0

那麼,謝謝,這可能是連字符中的連字符標題的二維部分拋出我的搜索,因爲我也使用2D而不是二維,因爲它給了我更多的結果 –

回答

1

您需要單獨輸入數組以輸入數字。所以,你可以做這樣的事情:

public class PrintArray { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     int[][] table = new int[4][4]; 
     for (int i = 0; i < table.length; i++) { 
      for (int j = 0; j < table.length; j++) { 
       // System.out.println("Enter a number."); 
       int x = input.nextInt(); 
       table[i][j] = x; 
      } 
      //System.out.println(); 
     } 
     // System.out.println(table); 

     for (int i = 0; i < table.length; i++) { 
      for (int j = 0; j < table[i].length; j++) { 
       System.out.print(table[i][j] + " "); 
      } 
      System.out.println(); 
     } 
    } 
} 
5

考慮使用java.util.Arrays

那裏有一種方法deepToString。這在這裏很有用。

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

與此有關:Simplest way to print an array in Java

+0

感謝您的幫助,如果我有代表,我會upvote您的答案,但顯然我的問題值得2 downvotes,這是非常有用的,我只是不太瞭解數組實用程序,所以我去了更復雜,但我更好地理解,只是修改我的FOR循環像湯加說,我一定會研究這一點,並嘗試學習更多關於你的答案。 –

+0

@AdamCalcanes聽起來不錯。我鏈接的帖子包含了很多關於如何完成此操作的信息。總是很好的學習新方法:D – Obicere

0

你必須回送通過這些數組內容打印出來。數組的toString()只是輸出參考值。

0

System.out.print(table)調用數組類中的一個方法,該方法輸出可放大的標識符。你需要創建一個for循環來打印出每個元素,比如System.out.print(table [i] [j]),或者使用Arrays類,並說Arrays.toString(table);

0

嘗試複製這種簡單的for循環來打印4×4表:

Scanner input = new Scanner(); 
    int numArray [] [] = new int [4] [4]; 
    for (int c = 0; c < 4; c++) { 
    for (int d = 0; d < 4; d++) { 
    System.out.print("Enter number : "); 
    nunArray [c][d] = input.nextInt(); 
    } 
    } 
    for (int a = 1; a<5;a++) { 
    for (int b = 1; b <5;b++) { 
    System.out.print(numArray [a][b]+" "); 
    } 
    System.out.println(); 
    } 
+0

@Adam Calcanes在代碼中有錯誤:第6行,變量應該是'numArray'而不是'nunArray'。第11行,也會生成java.lang.ArrayIndexOutOfBoundsException。 –