[java]代码库import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
int c = scan.nextInt();
System.out.println("row:"+r+" column:"+c);
//输入,修改矩阵的值
Matrix me = new Matrix(r,c);
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
double a = scan.nextDouble();
me.set(i, j, a);
}
}
r = scan.nextInt();
c = scan.nextInt();
double a = scan.nextDouble();
me.set(--r, --c, a);
System.out.println("after set value:");
me.show();
//打印具体位置上的值
r = scan.nextInt();
c = scan.nextInt();
System.out.print("value on ("+r+","+c+"):");
System.out.printf("%.0f\n",me.get(--r, --c));
//矩阵相加输出
r = scan.nextInt();
c = scan.nextInt();
Matrix jia = new Matrix(r,c);
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
a = scan.nextDouble();
jia.set(i, j, a);
}
}
System.out.println("after add:");
(me.add(jia)).show();
//矩阵相乘输出
r = scan.nextInt();
c = scan.nextInt();
Matrix cheng = new Matrix(r,c);
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
a = scan.nextDouble();
cheng.set(i, j, a);
}
}
System.out.println("after multiply:");
(me.multiply(cheng)).show();
//矩阵转置输出
System.out.println("after transpose:");
(me.transpose()).show();
}
}
class Matrix
{
private int row;//行
private int col;//列
double[][] m;
public Matrix(int a, int b)
{
row = a;
col = b;
m = new double [a][b];
}
void set(int r, int c, double a)
{
m[r][c] = a;
}
double get(int r, int c)
{
return m[r][c];
}
int width()
{
return col;
}
int height()
{
return row;
}
Matrix add(Matrix b)
{
Matrix a = new Matrix(row,col);
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
a.set(i,j, b.get(i,j)+this.m[i][j]);
}
return a;
}
Matrix multiply(Matrix b)
{
Matrix a = new Matrix(row,b.width());
for( int i = 0; i < row; i++)
{
for( int j = 0; j < b.width(); j++)
{
int sum = 0;
for( int k = 0; k < col; k++)
sum += this.get(i,k)*b.get(k, j);
a.set(i, j, sum);
}
}
return a;
}
Matrix transpose()
{
Matrix a = new Matrix(col,row);
for(int i = 0; i < col; i++)
{
for(int j = 0; j < row; j++)
a.set(i,j,this.m[j][i]);
}
return a;
}
void show()
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
if( j == 0)
System.out.printf("%.0f",this.get(i, j));
else
System.out.printf(" %.0f",this.get(i, j));
}
System.out.println();
}
}
}