有没有办法使用循环来改进这段代码?

我本质上是想找到一种更好的方法来使用循环编写此代码。Rational 和 Matrix 是我制作的类。为了创建一个 Matrix 对象,我需要四个 Rational 对象。


       Rational r1 = r.multiplyValue(array[0][0]);

       Rational r2 = r.multiplyValue(array[0][1]);

       Rational r3 = r.multiplyValue(array[1][0]);

       Rational r4 = r.multiplyValue(array[1][1]);


       return new Matrix(r1,r2,r3,r4);


侃侃尔雅
浏览 40回答 2
2回答

撒科打诨

假设你有一个Matrix这样的构造函数public Matrix(Rational...rationals){&nbsp; &nbsp; // TODO: initialize stuff}然后你可以迭代数组并Matrix像这样构造对象&nbsp; &nbsp; int[][] array = // Something useful&nbsp; &nbsp; Rational[] rs = new Rational[4];&nbsp; &nbsp; for(int i=0;i<array.length;i++){&nbsp; &nbsp; &nbsp; for(int j=0;j<array[i].length;j++){&nbsp; &nbsp; &nbsp; &nbsp; rs[i*2+j] = r.multipleValue(array[i][j]);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return new Matrix(rs);

拉风的咖菲猫

是的!你可以这样做,但你必须使用一些存储同类对象的集合或数据结构,例如列表或数组。下面的例子:&nbsp; &nbsp; &nbsp; &nbsp;List<Rational> list&nbsp; = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp;for(int i=0;i<=1;i++){&nbsp; &nbsp; &nbsp; &nbsp;for(int j=0;i<=1;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list.add(r.multiplyValue(array[i][j]));&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;return new Matrix(list); // modify constructor to accept list
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java