java二维数组的应用之矩阵的加法和乘法(知识点包含:数组的声明和初始化;数组的引用和输出;循环语句的应用)数学中的矩阵运算比较常见,在java中,设计二维数组来表示矩阵。这个例子要求随即产生两个矩阵,并实现两个矩阵的加法和乘法。具体的java矩阵相加与相乘实现代码如下:
//每一行(Row)数据用空格隔开,结束后回车
import java.io.*;
import java.util.*;
public class Arrtest{
public static void main(String args[]){
try{
System.out.print(“set the row of the arr:\n”);
BufferedReader in=new BufferedReader(
new InputStreamReader(System.in));
String row=in.readLine();
System.out.print(“set the line of the arr:\n”);
BufferedReader in2=new BufferedReader(
new InputStreamReader(System.in));
String line=in2.readLine();
int R=Integer.parseInt(row);
int L=Integer.parseInt(line);
Arr arr=new Arr();
System.out.print(“Great the first arr:\n”);
double arr1[][]=arr.greatArr(R,L);
System.out.print(“Great the second arr:\n”);
double arr2[][]=arr.greatArr(R,L);
arr.showArr(arr.addArr(arr1,arr2,R,L),R,L);
}catch(Exception e){e.getMessage(); }
}
}
class Arr {
double[][] greatArr(int row,int line){
double arr[][]=new double[row][line];
for(int i=0;i<row;i++){
try{
System.out.print(“input the row(“+(i+1)+”) numbers:\n”);
BufferedReader in=new BufferedReader(
new InputStreamReader(System.in));
String s=in.readLine();
StringTokenizer s_part=new StringTokenizer(s,” “);
for(int j=0;j<line;j++){
arr[i][j]=Double.parseDouble(s_part.nextToken());
}
}catch(Exception e){e.getMessage(); }
}
return arr;
}
double[][] addArr(double[][] arr1,double[][] arr2,int row,int line){
for(int i=0;i<row;i++){
for(int j=0;j<line;j++){
arr1[i][j]=arr1[i][j]+arr2[i][j];
}
}
return arr1;
}
void showArr(double[][] arr,int row,int line){
System.out.print(“the result:\r\n”);
for(int i=0;i<row;i++){
for(int j=0;j<line;j++){
System.out.print(arr[i][j]+” “);
}
System.out.print(“\r\n”);
}
}
}