Julian - 22 days ago 6

Java Question

So I would like to construct a program that receives the elements of two matrices and gives out the product of these two matrices. I experimented a little bit so far, created a matrix and used the "readInts"-manual. First, I would like to make sure that the program actually receives the elements typed in by the user, so I wanted to print out the first matrix as a whole (and then go further, of course). This is included in this code:

`int rows = readInt("Number of rows: ");`

int columns = readInt("Number of columns: ");

int [][] m = new int[rows][columns];

int [] elements = readInts("Please type in the elements: ");

for(int = 0; i < m.length; i++) {

print(elements[i], 5);

}

Now, what I didn't understand yet is how I have to interpret "m.length". After a little bit of testing, I found out that it refers to the number of rows, so for example when I define 3 rows and type in the numbers 1, 2, 3, 4, 5, I receive only 1, 2, 3, so the program cuts off the rest. I guess he actually is supposed to refer to the number of columns, so I'd have to switch [rows] and [columns] when I define m, but that's counterintuitive since you always name the number of rows first. Plus, I don't know whether there would arise other problems with that sooner or later or not. So, is there another way to do this without switching [rows] and [columns] at the beginning?

Answer

since you know the rows and columns you can do 2 for loops.

```
int rows = readInt("rows");
int columns =readInt("columns");
int [][] m = new int[rows][columns];
for (int i = 0; i < rows; i++) {
int n[]=readInts("enter 3 numbers:");
for (int k = 0; k < columns; k++) {
m[i][k] = n[k];
}
}
```

There is no need to use the scanner like i did(isn't working properly here). yet this should give you the desired result if you read the strings right