如何打印填充有 1 和 0 的二维数组?

时间:2021-01-07 21:06:36

标签: java

我正在尝试使用 1 和 0 打印二维数组(由用户指定大小)。但是,每次我尝试运行时,我都会得到随机数字和字母,例如“[[I@4eec7777”,而不是二维数组。我注释掉了 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);

1 个答案:

答案 0 :(得分:2)

问题

数组不会覆盖 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));
    }
    
}
相关问题