Reputation: 452
Hi I am stuck at this problem, input the elements in a 2D array where number of rows are known but number of columns are not known. But all the rows should have equal number of elements. How can i do this in java
like first input will be number of rows . then lines of input one for each row of the matrix .Each row will contain the same number of columns and each column separated by a space.
I tried this, but it is not working
System.out.println("Enter the number of rows");
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int [] [] matrix = new int [N][N];
int row=0;
int col =0;
while(sc.hasNextInt() && N<=col)
{System.out.println("Enter the elements");
matrix[row][col++]=sc.nextInt();
col++;
}
for(int i=1; i<=N; i++)
{
for(int j =0; j<=col;j++)
{System.out.println("enter the elements");
matrix[i][j]=sc.nextInt();
}
}
Upvotes: 0
Views: 57
Reputation: 1922
If you don't know the number of columns, you can do something like this:
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
sc.nextLine(); // nextInt() didn't consume the newline so we do it here
int[][] matrix = new int[rows][];
for (int i = 0; i < rows; i++) {
String line = sc.nextLine();
String[] valueStrings = line.split("\\s+");
matrix[i] = new int[valueStrings.length];
for (int j = 0; j < valueStrings.length; j++) {
matrix[i][j] = Integer.parseInt(valueStrings[j]);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print("" + matrix[i][j] + " ");
}
System.out.println();
}
Input:
3
1 2 3 4
5 6 7 8
9 0 1 2
Output:
1 2 3 4
5 6 7 8
9 0 1 2
edit: fixed the wrong nesting
Upvotes: 1
Reputation: 22254
You seem to want to read a matrix with known number of rows and columns. This should do that :
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[][] matrix = new int[N][N];
System.out.println("Enter the elements");
for (int row = 0; row < N; ++row) {
for (int col = 0; col < N; ++col) {
matrix[row][col] = sc.nextInt();
}
}
In your attempt you need to think more about why you are incrementing col twice, why you are comparing for less or equal to N and why the for loop starts from 1 and not 0.
Upvotes: 0