I'm trying to figure out how to read in a multidimensional array from standard input given the user provides the row and col size followed by integers of the array
e.g. Input:
2 3 <= row, col of array
8 3 10 < array integers
7 9 6
My code is currently:
int colA = scan.nextInt();
int rowA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i <rowA;i ){
for (int j=0; j<colA;j ){
array1[i][j] = scan.nextInt();
}
}
And the output of my array is: [[8,3,10,7,9,6]] but what I'd like to do is output [[8,3,10],[7,9,6]]
CodePudding user response:
Here first the row and col value got from users is reversed that is the only mistake i could see import java.util.Arrays; import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rowA = scan.nextInt();
int colA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i < rowA; i ) {
for (int j = 0; j < colA; j ) {
array[i][j] = scan.nextInt();
}
}
for (int[] innerArray : array) {
System.out.println(Arrays.toString(innerArray));
}
}
} This is a working one
CodePudding user response:
There are some errors in your code.
You inverted the order of the dimensions asked to the users.
Use this:
int rowA = scan.nextInt(); int colA = scan.nextInt();
Instead of this:
int colA = scan.nextInt(); int rowA = scan.nextInt();
You wrote
array1
instead ofarray
inarray1[i][j] = scan.nextInt();
Note that you can use array[i][j] = scan.nextInt();
instead of array[i][j] = scan.nextInt()