gpt4 book ai didi

java - 如何在两个分数矩阵之间进行加法

转载 作者:行者123 更新时间:2023-12-01 11:36:37 25 4
gpt4 key购买 nike

我有一个 Matrix 类 fillMatrix()printMatex()方法,它是分数矩阵并使用 hashmap 填充:HashMap <Integer, ArrayList<Number>> (具有行和列格式)

Number是一个具有分数加法和减法方法的类。我要求在 Matrix 中创建一个方法类在两个矩阵之间进行加法,如下所示:

The class has a public void addMatrices (Matrix, Matrix) which has 2 matrices as arguments and it calculates the summation of these matrices.

我写了这段代码,但它不起作用。它给了我这个错误:

Incompatible types: ArrayList<Number>cannot be converted  to Number

这是我的代码

  public void addMatrices(Matrix m1, Matrix m2) {    
HashMap<Integer, ArrayList<Number>> matrix3 = new HashMap<Integer, ArrayList<Number>>();

HashMap<Integer, ArrayList<Number>> matrix1 = m1.hMap;
HashMap<Integer, ArrayList<Number>> matrix2 = m2.hMap;

Number ob = new Number();

for (int i = 1; i <= rows; i++) {
for (int j = 0; j <= cols; j++) {
matrix3.put(i, ob.addition(matrix1.get(j), matrix2.get(j)));
}
}
}

最佳答案

问题是你的变量matrix3是类型

HashMap<Integer, ArrayList<Number>>

如果你想将一个值放入 HashMap 中,则需要以下类型

put(Integer as key, ArrayList<Number> as value);

但是你调用number类的add方法,并将结果作为值放入put方法中,我认为结果也是一个数字。\

所以问题出在这一行:

matrix3.put(i, ob.addition(matrix1.get(j),matrix2.get(j)));

要么将matrix3类型更改为

HashMap<Integer, Number>

或者您在添加后将数组列表作为值:

List<Numbers> n = new ArrayList<Number>();
n.add(ob.addition(matrix1.get(j),matrix2.get(j)));
matrix3.put(i, n);

关于java - 如何在两个分数矩阵之间进行加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com