猿问

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

我正在尝试使用用户的输入制作一个二维数组。但是,我的代码中的变量是固定的。因此,当用户输入整数 x 时,二维数组没有 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

我感谢任何帮助或建议!


PIPIONE
浏览 111回答 2
2回答

至尊宝的传说

这里: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++) {&nbsp; for (int j = 0; j < n; j++) {&nbsp; &nbsp; twoD[i][j] = (int) (Math.random() * 2);&nbsp; }}for (int[] x : twoD) {&nbsp; for (int y : x) {&nbsp; &nbsp; System.out.print(y + "&nbsp; ");&nbsp; }&nbsp; System.out.println();}输出:Enter the size of the array: 41&nbsp; 0&nbsp; 0&nbsp; 0&nbsp;&nbsp;1&nbsp; 0&nbsp; 0&nbsp; 1&nbsp;&nbsp;0&nbsp; 1&nbsp; 0&nbsp; 0&nbsp;1&nbsp; 0&nbsp; 1&nbsp; 1&nbsp;

湖上湖

我假设你想这样做: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) {&nbsp; &nbsp; for (int j : i) {&nbsp; &nbsp; &nbsp; &nbsp; j = rand.nextInt(2);&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(j + " ");&nbsp; &nbsp; }System.out.println("\n");
随时随地看视频慕课网APP

相关分类

Java
我要回答