栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java利用list创建二维数组并实现相乘相加

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java利用list创建二维数组并实现相乘相加

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531008.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号