2014-01-06 43 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。 –