import java.util.*;
//由于数组长度不确定,因此我用ArrayList实现
public class ArrayMatrix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入生成稀疏矩阵的行和列:");
int x1 = input.nextInt();//行
int y1 = input.nextInt();//列
System.out.println("请输入矩阵元素:");
int[] arr1 = new int[x1 * y1];
try{ //利用异常处理捕捉异常
for (int i = 0; i < x1 * y1; i++) {
arr1[i] = input.nextInt();
}
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("输入矩阵大小发生错误");
}
Matrix m = new Matrix(x1, y1, arr1);
m.returnMatrix();
System.out.println("----------------------------------");
System.out.println("请输入生成稀疏矩阵的行和列:");
int x2=input.nextInt();//行
int y2=input.nextInt();//列
System.out.println("请输入矩阵元素:");
int []arr2=new int[x2*y2];
try {
for (int i = 0; i < x2 * y2; i++) {
arr2[i] = input.nextInt();
}
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("输入矩阵大小发生错误");
}
Matrix s = new Matrix(x2, y2, arr2);
s.returnMatrix();
// Matrix c1=m.plusMatrix(s);
// c1.returnMatrix();
Matrix c2=m.mulMatrix(s);
c2.returnMatrix();
}
}
class Matrix{
public int row,col;
public ArrayList []list1;
Matrix(int a,int b,int []input){
this.row=a;
this.col=b;
list1 = new ArrayList[col];//先创建列链表
for(int i = 0; i < col; i++) {
list1[i] = new ArrayList();//列链表的每一个元素都是一个链表,形成矩阵
}
int length2=0;
for(int j=0;j= this.col) {
System.out.println(" "); //如果长度超过列长,则换行
length=0; //下一行的初始长度重置为0
}
}
}
}
public Matrix mulMatrix(Matrix a){ //实现矩阵的相乘运算
int []arr=new int[this.row*a.col];
Matrix c=new Matrix(this.row,a.col,arr);
int []sum=new int[this.row*a.col];
int length3=0;
if(this.col==a.row){
for(int i = 0; i < this.row; i++){
for(int k = 0; k < a.col; k++) {
for (int j = 0; j < a.row; j++) {
sum[length3]=((int) this.list1[j].get(i) * (int) a.list1[k].get(j))+sum[length3];
}
length3++;
}
}
}
else{
System.out.println("不满足相乘条件!");
}
length3=0;
for(int w=0;w