Java 两个带螺纹矩阵的乘积
我不太擅长编程,但我必须编写一个程序,用两种方法计算两个矩阵的乘积: 第一种方法是直接的 第二种方法使用线程,因此计算时间最小 我为第一种方法编写了这个程序: Matrix.javaJava 两个带螺纹矩阵的乘积,java,Java,我不太擅长编程,但我必须编写一个程序,用两种方法计算两个矩阵的乘积: 第一种方法是直接的 第二种方法使用线程,因此计算时间最小 我为第一种方法编写了这个程序: Matrix.java public class Matrix { public int [][] M; public int line,col; static int [][]MProd=null; //Constructeur public Matrix (int [][] M,i
public class Matrix {
public int [][] M;
public int line,col;
static int [][]MProd=null;
//Constructeur
public Matrix (int [][] M,int line,int col) {
this.M=M;
this.col=col;
this.line=line;
for ( int i=0;i<this.line;i++){
for (int j=0;j<this.col;j++)
{
M[i][j]=(int)(Math.random()*100);}}
}
static int [][] prod(Matrix Mat1, Matrix Mat2 ){
for (int j=0;j<Mat2.col;j++){
for (int i=0;i<Mat1.col;i++){
for (int k=0;k<Mat1.line;k++){
MProd[k][j] += Mat1.M[k][i]*Mat2.M[i][j];
}}}
return MProd ;
}}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int [][] M = null,N = null;
int line1,line2,col1,col2;
int [][] P=null;
Scanner scanner = new Scanner(System.in);
System.out.println("enter the line number of the first matrix");
line1=scanner.nextInt();
System.out.println("enter the number of columns of the first matrix");
col1=scanner.nextInt();
Matrix Mat= new Matrix (M,line1,col1);
System.out.println("enter the line number of the 2nd matrix");
line2=scanner.nextInt();
System.out.println("enter the number of columns of the 2nd matrix");
col2=scanner.nextInt();
Matrix Mat1= new Matrix (N,line2,col2);
if (col1==line2)
{
P=Matrix.prod(Mat,Mat1) ;
System.out.println("matrix product :");
for (int i=0;i<Mat.line;i++)
{
for (int j=0;j<Mat1.col; j++)
System.out.print( + P[i][j]+" ");
System.out.println();
}}
else {
System.out.println("the matrices product is impossible");
}
}}
公共类矩阵{
公共int[][]M;
公共内线;
静态int[]MProd=null;
//建设者
公共矩阵(int[][]M,int行,int列){
这个,M=M;
this.col=col;
这条线=线;
对于(int i=0;i您的NullPointerException是由以下原因引起的:
public static void main(String[] args) {
int [][] M = null,N = null; // all declared null
// ...
Matrix Mat= new Matrix (M,line1,col1); // here you use a null value, M
// ...
Matrix Mat1= new Matrix (N,line2,col2); // and same here, N is null
调用矩阵类中的,M[i][j]=(int)(Math.random()*100);
时,M为null,因此将失败。必须先创建一个矩阵,即2D数组,然后才能使用它
编辑
你问:
你能再给我解释一下吗
您正在将null引用传递到矩阵构造函数中,然后尝试将其用作变量。您应该传递非null 2D数组:
int[][] myArray = new int[x][y]; // where x and y are appropriate numbers
Matrix Mat= new Matrix (myArray, line1, col1);
此外,请学习和使用标准(请参见链接),包括:
- 所有类、枚举和接口名称都以大写字母开头
- 所有方法和变量名都以小写字母开头
- 学习明智地使用空格,包括参数之间的空格
这样做,人们将能够更好地阅读和理解您的代码,然后能够为您提供更好的帮助。您以前发布过,因此您知道该练习:1)请指定“不工作”的含义。2)请提出具体问题,作为第二个问题,“…如何使用线程编写此程序”这是我第一次在这里发表文章:)啊,你的分数愚弄了我。很抱歉,我直截了当地说,但是,我仍然认为,如果你努力改进你的问题。再说一遍,“不起作用”提供的信息很少,我们可以用来帮助您。同样,您的问题的第二部分太宽泛了。在显示代码尝试之后,我们回答特定的有针对性的问题会做得更好。@HovercraftFullOfEels现在这很好?哪一行是Matrice.java类的第18行,如Matrice.java:18
中所述?现在还没有,关于第二部分,您仍然需要提出一个或多个具体问题。我们不知道您可能会遇到什么问题。