简体   繁体   English

如何获取用户的输入来制作二维数组?

[英]How do take an user's input to make a two-dimensional array?

I am trying to make a two-dimensional array using the inputs from the user.我正在尝试使用用户的输入制作一个二维数组。 However, the variables in my code are fixed.但是,我的代码中的变量是固定的。 Thus, when a user inputs an integer x, the two-dimensional array does not have x rows and columns.因此,当用户输入一个整数 x 时,二维数组没有 x 行和列。 How can I fix my code?我该如何修复我的代码?

This is what I have so far:这是我到目前为止:

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]);

The output should instead look like the following:输出应如下所示:

Enter the size of the array: 3

0 1 0

1 0 1

0 1 1

I appreciate any help or suggestions!我感谢任何帮助或建议!

I assume you want to do this:我假设你想这样做:

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");

Here:这里:

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();
}

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM