日期:2014-05-20 浏览次数:20804 次
public class Matrix { private Object[][] matrix; private int height,width;//行,列 Matrix(){} Matrix(int h,int w){ height=h;//矩阵行数 width=w;//矩阵列数 } public void set(int row,int col,Object value)//将value插入row行,col列中 { matrix=new Object[height][width]; if(row>height||row<=0||col<=0||col>width) { System.out.println("此项不存在!"); } matrix[row-1][col-1]=value; } public Object get(int row,int col) { return matrix[row-1][col-1]; } public int width(){//返回矩阵的列 return width; } public int height(){//返回矩阵的行 return height; } public Matrix add(Matrix b)//矩阵相加 { Matrix a=new Matrix(); int i,j; if(height!=b.height()||width!=b.width()) { return null; } else { for(i=0;i<height;i++) { for(j=0;j<width;j++) { String m=matrix[i][j].toString(); String n=b.matrix[i][j].toString(); int value=Integer.parseInt(m)+Integer.parseInt(n); a.set(i, j, value); } } return a; } } public Matrix multiply(Matrix b) { Matrix a=new Matrix(); if(width!=b.height()) { return null; } else { for(int i=0;i<height;i++) { for(int j=0;j<b.width();j++) { int value=0; for(int k=0;k<width;k++) { String m=matrix[i][k].toString(); String n=b.matrix[k][j].toString(); value+=Integer.parseInt(m)+Integer.parseInt(n); a.set(i+1, j+1, value); } } } return a; } } public void print() {// 打印出当前矩阵的值 if(width!=0||height!=0){ for (int i = 0; i < height; i++) { System.out.print("|\t"); for (int j = 0; j < width; j++) { System.out.print(matrix[i][j] + "\t"); } System.out.print("|\n"); } } else { System.out.println("该矩阵不存在。"); } } public static void main(String[] args){ Matrix a=new Matrix(2,2); a.set(1,1,1); a.set(1,2,2); a.set(2,1,3); a.set(2,2,4); a.print(); } }