如果我有一个数组int[] a = new int[]{1, 2, 3};
和另一个int[] b = new int[]{3, 2};
我想将两者加在一起,我会这样做:
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 被遗漏了,我哪里出错了?
预先感谢您的任何帮助!
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})
)
您可以定义一个目标数组,其长度为两个源数组的最大值。之后,您只需进行数组边界检查。当然,您还应该在开始循环之前添加对 null 的检查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));
}
}
Output:
[4, 4, 3]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)