如何打印充满1和0的二维数组



我正在尝试打印一个包含1和0的2D数组(大小由用户指定(。然而,每次我尝试跑步时,我都会得到随机的数字和字母,比如";[[I@4eec7777"而不是2D数组。我注释掉了for循环,认为我已经将问题缩小到了数组的初始化?我不确定我做错了什么。

System.out.print("How many rows? : ");
int numRows = userInput.nextInt(); //numRows works
System.out.print("How many columns? : ");
int numCols = userInput.nextInt(); //numCols works
int randomArray[][] = new int[numRows][numCols]; 
//    for (int row = 0; row < randomArray.length; row++) {
//      int temp = (int) ((Math.random()*2)+1);
//      for (int col = 0; col < randomArray[row].length; col++) {
//        if (temp % 2 == 0) randomArray[row][col] = 1;
//      }
//    }
System.out.println(randomArray);

问题

数组不会覆盖Java中的toString((方法。如果你尝试直接打印一个,你会得到className+@+数组hashCode的十六进制,由Object.toString((定义;

解决方案

从Java 5开始,您可以使用Arrays.toString(arr(或Arrays.deepToString(arr。请注意,Object[]版本对数组中的每个对象调用.toString((

因此,您可以通过轻松打印嵌套数组

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

这里是完整的代码

import java.util.*;
public class Whatever {
public static void main(String[] args) {

Scanner userInput = new Scanner(System.in);

System.out.print("How many rows? : ");
int numRows = userInput.nextInt(); //numRows works
System.out.print("How many columns? : ");
int numCols = userInput.nextInt(); //numCols works
int randomArray[][] = new int[numRows][numCols]; 
for (int row = 0; row < randomArray.length; row++) {
int temp = (int) ((Math.random()*2)+1);
for (int col = 0; col < randomArray[row].length; col++) {
if (temp % 2 == 0) randomArray[row][col] = 1;
}
}
System.out.println(Arrays.deepToString(randomArray));
}

}

最新更新