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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.