There two string Arrays, array1 and array2.
String[] array1 = {“1”, “2”, “3”, “4”,”5″,”6″,”7″}
String[] array2= {“apple”, “”, “”, “banana”, “”, “”, “orange”};
Could you please help me with a java code to produce output like
String[] desiredOutput = {“1″,”5″,”4″,”11″,”7”}
Logic: whereever there is empty value in array2, add the corresponding values in array1
Example:
array2[0] = “apple”, so desired output is value of array1[0], output ={“1”}
array2[1] = “” and
array2[2] = “” so desired output is sum of (array1[1]+array1[2]) , output ={“1″,”5”}
array2[3] = “banana”, so desired output is value of array1[3], output ={“1″,”5″,”4”}
array2[4] = “” and
array2[5] = “” so desired output is sum of (array1[4]+array1[5]) , output ={“1″,”5″,”4″,”11”}
array2[6] = “orange”, so desired output is value of array1[6], output ={“1″,”5″,”4″,”11″,”7”}
Thanks
It tried this ,. but failed
String[] array1 = {“1”, “2”, “3”, “4”, “5”, “6”, “7”};
String[] array2 = {“apple”, “”, “”, “banana”, “”, “”, “orange”};
// Calculate concatenated values and add them to a new array
String[] concatenatedArray = new String[array1.length];
for (int i = 0; i < array1.length; i++) {
int value1 = Integer.parseInt(array1[i]);
int value2 = (array2[i].isEmpty()) ? 0 : Integer.parseInt(array2[i]);
concatenatedArray[i] = String.valueOf(value1 + value2);
}
// Print the concatenated array in the desired format
System.out.print("(");
for (int i = 0; i < concatenatedArray.length; i++) {
System.out.print(""" + concatenatedArray[i] + """);
if (i < concatenatedArray.length - 1) {
System.out.print(",");
}
}
System.out.println(")");
Meenu Sai is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.