【发布时间】:2019-04-16 23:04:02
【问题描述】:
所以我在当地高中帮助辅导代数 2 课程,该课程目前正在查看矩阵。虽然不在那里,但他们最终会得到矩阵的乘法。在去年学习了计算机科学并学习了 Java 之后,我帮助的老师认为我应该尝试为多个矩阵编写程序。
目前,我需要定义第一个数组的数字,该数组包含第一个矩阵的信息。不过,我有一个小问题。如图所示:
在已经记录整数之后,要求索引整数的行正在重复。我认为这是由于我的分层 for 循环,但我不能确定。通常新的眼睛会更清楚地看到问题。任何可以帮助我的人将不胜感激。
代码:
package matrixmultiplication;
import java.util.*;
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("What is the size of the first matrix?");
int matrix1Rows = matrixRows();
int matrix1Columns = matrixColumns();
int[] matrix1 = new int[matrix1Rows * matrix1Columns];
doubleSpace();
System.out.println("What is the size of the second matrix?");
int matrix2Rows = matrixRows();
int matrix2Columns = matrixColumns();
int[] matrix2 = new int[matrix2Rows * matrix2Columns];
doubleSpace();
if (matrix1Columns != matrix2Rows) {
System.out.println("These cannot be multiplied!");
System.exit(0);
} else {
matrix1Numbers(matrix1Rows, matrix1Columns);
}
}
public static int matrixRows() {
System.out.print("Rows:");
Scanner rowSc = new Scanner(System.in);
int rows = rowSc.nextInt();
return rows;
}
public static int matrixColumns() {
System.out.print("Columns:");
Scanner colSc = new Scanner(System.in);
int cols = colSc.nextInt();
return cols;
}
public static int[] matrix1Numbers(int rows, int cols) {
int[] numb = new int[rows * cols];
for (int j = 0; j <= numb.length; j += rows) {
for (int i = 1; i <= cols; i++) {
for (int k = 1; k <= rows; k++) {
System.out.println("What is the value for index ("
+ k + "," + i + ")?");
Scanner inp = new Scanner(System.in);
if (j + k <= numb.length) {
numb[j + k - 1] = inp.nextInt();
}
}
}
}
for (int i = 0; i < numb.length; i++) {
System.out.println(numb[i]);
}
return numb;
}
public static void doubleSpace() {
System.out.println();
System.out.println();
}
}
我使用 NetBeans 8.2 和适用于 NetBeans 的最新 Java 工作版本。
【问题讨论】:
-
您是否意识到您可以在 Java 中使用
int[][]?对于行j、列k的项目,写numb[j][k]而不是numb[j * cols + k]要方便得多。 -
在任何情况下,您都不需要额外的循环嵌套级别。第一级遍历行,接下来遍历列,第三级遍历行再次。
标签: java arrays debugging matrix matrix-multiplication