利用二维数组实现一个矩阵类:Matrix。要求提供以下操作:(1)set(int row, int col, Object value):将第row行第col列的元素赋值为value;(2)get(int row,int col):取第row行第col列的元素;(3)width():返回矩阵的列数;(4)height():返回矩阵的行数;(5)Matrix add(Matrix b):返回当前矩阵与矩阵b相加后的结果矩阵;(6)Matrix multiply(Matrix b):返回当前矩阵与矩阵b相乘后的结果矩阵。(7)print():打印出当前矩阵的值。

解决方案 »

  1.   

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class Matrix {
    int row,col;
    double [][]value=new double[row][col];
    Matrix(){}
    Matrix(int row, int col){
    this.row=row;this.col=col;
    }
    void set(int row,int col){   //设置矩阵为row+1行,col+1列,并且输入值赋给value
    int r=row+1,c=col+1;
    System.out.println("矩阵为"+r+"行"+c+"列");
    this.row=row;
    this.col=col;
    this.value=new double[row+1][col+1];
    int i,j;
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    for(i=0;i<=row;i++){
    for(j=0;j<=col;j++){
    try{r=i+1;c=j+1;
    System.out.println("输入矩阵第"+r+"行"+","+"第"+c+"列元素");
    this.value[i][j]=Double.parseDouble(in.readLine());
    }catch(IOException e){}
    }
    }
    }
    double get(int row,int col){    //返回矩阵row行,col列的值
    double a=0;
    if(this.row>=row &&this.col>=col){
    a=value[row][col];
    }
    else System.out.println("输入的值不存在,返回值为0");
    return a;
    }
     int width(){   
     return this.col;
     }
     int height(){
     return this.col;
     }
     Matrix Matrixadd(Matrix other){
     Matrix x=new Matrix();
     int i,j;
     if(this.row==other.row && this.col==other.col){
     x=new Matrix(this.row,this.col);
     x.value=new double[this.row+1][this.col+1];
     for(i=0;i<=row;i++){
    for(j=0;j<=col;j++){
    x.value[i][j]=this.value[i][j]+other.value[i][j];
    }
     }
     x.print();
     }
     else System.out.println("两矩阵不能相加");
     return x;
     }
     Matrix Matrixmultiply(Matrix other){
     Matrix a =new Matrix();
     int i,j;
     double s = 0;
     if(this.row==other.row && this.col==other.col){
     a=new Matrix(this.row,this.row);
     a.value=new double[this.row+1][this.col+1];
     for(i=0;i<=row;i++){
    for(j=0;j<=col;j++){
    for(int x=0;x<=col;x++){
    s=this.value[i][x]*other.value[x][i];
    }
    a.value[i][j]=s+a.value[i][j];
    }
     }
     a.print();
     }
     else System.out.println("两矩阵不能相乘法");
     return a;
     }
     void print(){
     int i,j;
    for(i=0;i<=row;i++){
    System.out.println("");
    for(j=0;j<=col;j++){
    System.out.print(this.value[i][j]);
    }
    }
     }
    }
      

  2.   

    Object类型的矩阵怎么运算