如何添加两个不同大小的数组? [英] How to add two different sized arrays?
问题描述
如果我有一个数组 int [] a = new int [] {1、2、3};
和另一个 int [] b = new int [] {3,2};
,我想将两者加在一起,我会这样做:
If I have an array int[] a = new int[]{1, 2, 3};
and another int[] b = new int[]{3, 2};
and I want to add the two together, I would do:
if (a.length >= b.length){
int[] c = new int[a.length];
for(int i=0; i<c.length; i++){
c[i] = a[i] + b[i];
return c;
}
}
else{
int[]c = new int[b.length];
for(int i=0; i<c.length; i++){
c[i] = a[i] + b[i];
return c;
}
但是当我打印c时,得到{4,4}和3最后被排除在外,我在哪里错了?
But when I print c, I get {4, 4} and the 3 on the end is left out, where am I going wrong?
在此先感谢您的帮助!
public Poly add(Poly a){
if (coefficients.length <= a.coefficients.length){
int[] c = new int[coefficients.length];
for (int i=0; i<added.length; i++){
c[i] = a.coefficients[i] + coefficients[i];
}
Poly total = new Poly(c);
return total;
}
else{
int[] added = new int[a.coefficients.length];
for (int i=0; i<added.length; i++){
added[i] = a.coefficients[i] + coefficients[i];
}
Poly total = new Poly(c);
return total;
}
}
Poly是一个构造函数,它使用int数组作为一个参数( Poly ex = new Poly(new int [] {1,2,3})
)
and Poly is a constructor that takes an int array as an argument (Poly ex = new Poly(new int[]{1, 2, 3})
)
推荐答案
您可以定义一个目标数组,其长度为两个源数组的最大值。之后,您只需要进行数组边界检查即可。当然,在开始循环 c
之前,还应该添加null检查。
You can define a destination array with a length of the max of both source arrays. After that you just do array bounds-checking. Of course, you should also add checks for null before you even begin to loop over c
.
import java.util.Arrays;
class AddArrays {
private static int[] a = new int[] { 1, 2, 3 };
private static int[] b = new int[] { 3, 2 };
private static int[] c = add(a, b);
private static int[] add(int[] a, int[] b) {
int[] c = new int[(int) Math.max(a.length, b.length)];
for (int i = 0; i < c.length; i++) {
if (a.length > i) {
c[i] += a[i];
}
if (b.length > i) {
c[i] += b[i];
}
}
return c;
}
public static void main (String[] args) {
System.out.println(Arrays.toString(c));
}
}
输出:
[4, 4, 3]
这篇关于如何添加两个不同大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!