简体   繁体   English

二维数组/矩阵的长度

[英]Length of a 2-dimensional array / matrix

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. 到目前为止,我进行了一些实验,创建了一个矩阵,并使用了“ readInts”手册。 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". 现在,我还不了解的是如何解释“ 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. 经过一点测试,我发现它指的是行数,因此,例如,当我定义3行并键入数字1、2、3、4、5时,我只收到1、2、3 ,因此该程序会切断其余部分。 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. 我猜他实际上应该指的是列数,因此在定义m时我必须切换[行]和[列],但这是违反直觉的,因为您总是先命名行数。 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? 因此,还有另一种方法可以在开始时不切换[行]和[列]的方法吗?

since you know the rows and columns you can do 2 for loops. 由于您知道行和列,因此可以执行2个for循环。

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 但是,如果您正确阅读字符串,这应该可以为您提供所需的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM