/** * @author LZY * @time 2021/11/16 * @text SZU homework7 */ 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<row;j++) { //当每一列的第j个元素都被添加进list后换行 for (int i = 0; i <col; i++) { list1[i].add(input[length2]); //每一列都按行增加元素 length2++; } } } public void returnMatrix(){ int length=0;//初始长度为0 for(int j=0;j<this.row;j++) { for (int i = 0; i < this.col; i++) { System.out.print(this.list1[i].get(j)+" ");//输出该行下每一列的元素 length++; if(length>= 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<this.row;w++){ for(int l=0;l<a.col;l++){ c.list1[l].set(w,sum[length3]); length3++; } } return c; } public Matrix plusMatrix(Matrix b) { //实现矩阵的相加 int[] arr = new int[this.row * this.col]; Matrix c = new Matrix(this.row, this.col, arr); if (this.row == b.row && this.col == b.col) { for (int i = 0; i < this.row; i++) for (int j = 0; j < this.col; j++) { int value = (int) this.list1[j].get(i) + (int) b.list1[j].get(i); c.list1[j].set(i, value); } return c; } else{ System.out.println("不满足相加条件!"); return null; } } }
java利用list创建二维数组并实现相乘相加
最新推荐文章于 2023-02-27 21:15:58 发布