【发布时间】:2017-09-10 20:29:56
【问题描述】:
我必须编写一个程序,提示用户输入二维矩阵的维度以及矩阵的值。
之后,我必须将矩阵乘以 2 并打印结果。
我的程序快完成了,但我不知道如何将矩阵相乘并将这些值存储到一个新矩阵中。到目前为止,这是我的代码:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the number of rows: ");
int row = sc.nextInt();
System.out.println("Please enter the number of columns: ");
int col = sc.nextInt();
int[][] matrix = new int[row][col];
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: ");
for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix[row].length; col++) {
matrix[row][col] = sc.nextInt();
}
}
System.out.println();
for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
我到处寻求帮助并尝试了几种不同的说法,但似乎没有一个是完全正确的。
我知道我必须使用for 循环,但就像我说的我不完全确定要使用多少,如何将新值存储在矩阵中并显示它等等。
任何方向将不胜感激!
【问题讨论】:
-
您应该定义一个 Matrix 类并将您的数据存储在那里。 tutorialspoint.com/java/java_object_classes.htm
标签: java matrix multidimensional-array