如何接受用户的输入来制作二维数组?

时间:2019-02-28 21:21:13

标签: java arrays

我正在尝试使用来自用户的输入创建二维数组。但是,我的代码中的变量是固定的。因此,当用户输入整数x时,二维数组没有x行和列。如何修复我的代码?

这是我到目前为止所拥有的:

Scanner s = new Scanner (); 
int size = s.nextInt();
    int a1 = new int [size]; 
    int a2 = new int [size];
    int a3 = new int [size];
for (int i = 0; i<= size; i++) {
    int value = (int)(Math.random()*1); 
    a1[i] = value; 
    int value = (int)(Math.random()*1); 
    a2[i] = value; 
    int value = (int)(Math.random()*1); 
    a3[i] = value; 
System.out.print(a1[i] + " " + a2[i] + " " + a3[i]);

输出应改为如下所示:

Enter the size of the array: 3

0 1 0

1 0 1

0 1 1

感谢您的帮助或建议!

2 个答案:

答案 0 :(得分:-1)

我认为您想这样做:

System.out.println("Please enter two-dimentional array size:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Random rand = new Random();;
int[][] array = new int[n][n];
for (int[] i : array) {
    for (int j : i) {
        j = rand.nextInt(2);
        System.out.print(j + " ");
    }
System.out.println("\n");

答案 1 :(得分:-1)

这里:

System.out.print("Enter the size of the array: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int twoD[][] = new int[n][n];

for (int i = 0; i < n; i++) {
  for (int j = 0; j < n; j++) {
    twoD[i][j] = (int) (Math.random() * 2);
  }
}
for (int[] x : twoD) {
  for (int y : x) {
    System.out.print(y + "  ");
  }
  System.out.println();
}

输出:

Enter the size of the array: 4
1  0  0  0  
1  0  0  1  
0  1  0  0 
1  0  1  1