I've seen similar questions and none provide the answer that I'm looking for, so I apologize in advance if this is considered a duplicate. I'm trying to combine arrays {2, null, 3} and {4, 5, 6} into {6, 5, 9}. Sorry if the question is stupid.
You can simply do a for loop:
int[] newArray = new int[array1.length]();
for(int i = 0; i < array1.length; i ++){
int sum = (array1[i] == null ? 0 : array1[i]) + (array2[i] == null ? 0 : array2[i]);
newArray[i] = sum;
}
You should consider the two array might not be of the same size
int size1 = array1.length;
int size2 = array2.length;
int[] newArray = new int[size1 > size2 ? size1 : size2];
for(int i = 0; i < newArray.length; i ++){
int sum = 0;
if(size1 >= i && size2 >= i){
sum = (array1[i] == null ? 0 : array1[i]) + (array2[i] == null ? 0 : array2[i]);
} else if(size1 >= i && size2 < i){
sum = array1[i] == null ? 0 : array1[i];
} else{
sum = array2[i] == null ? 0 : array2[i];
}
newArray[i] = sum;
}
Note: I did it as you asked, but int is always != null, the default value is 0
I wrote it by hand so it might be not perfect, hope this helped
You can do something like this
public Integer[] arraySum(Integer[] array1, Integer[] array2) {
if (array1.length != array2.length) {
throw new IllegalArgumentException("Arrays should have the same size.");
}
Integer[] result = new Integer[array1.length];
for (int i = 0; i < array1.length; i++) {
result[i] = getValue(array1[i]) + getValue(array2[i]);
}
return result;
}
private int getValue(Integer integer) {
return integer == null ? 0 : integer;
}
也许您主要需要:
a3[i] = (a1[i] == null ? a1[i] : 0) + (a2[i] == null ? a2[i] : 0);
private static String[] arrayMeger(String[] arr1,String[] arr2 ){
String[] returnArr = new String[arr1.length()];
for(int i=0;i<arr.length();i++)
{
int valInt = (arr[i]==null) ? 0 : Integer.parse(arr[i]);
int valInt2 = (arr2[i]==null) ? 0 : Integer.parse(arr2[i]);
returnArr [i] = Integer.toString(valInt +valInt2 );
}
return returnArr ;
}
array is very old concept you should have a look at Array List
For know in your case i consider two static array with 3 element in it
int[] A = {2, null, 3};
int[] B = {4, 5, 6} ;
int[] C= new int[3]
for(int i=0;i<3;i++){
C[i] = (A[i]==null?A[i]:0) + (B[i]==null?B[i]:0);
}
//C array is your final array but make sure you remove null from your code
I think you may need this, Try these lines of code, they may help
int[] a = {2, null,3};
int[] b = {4, 5,6};
int c[a.length()];
for(int i = 0;i < 3;i++){
c[i] = (a[i]==null?a[i]:0) + (b[i]==null?b[i]:0)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.