-4

This may be a completely trivial question but i cannot find any documentation on this... I want to find the sum of two individual array elements for example....

array3[x] = array1[y] + array2[z]

when I do something like this, the answer is y and z combined. how would one find the sum of numbers y & z and not the conjoined string. Sorry if this is exceedingly trivial but i could not find a post asking this myself.

in summary if I have an array eg: a[1,2,5,9] & b[8,6,7,2] & c[]

c[0] = a[0] + b[0]
System.out.println(c[0]);
 "9"
Josh
  • 49
  • 8

3 Answers3

1

If you want to use string array you can do

String[] a={"1","2"};
String[] b={"1","2"};
String[] c=new String[1];
c[0]=String.valueOf(Integer.parseInt(a[1])+Integer.parseInt(b[1]));
System.out.println(c[0]);  // outputs 4

Demo

Note: but be sure that string array contains integer value otherwise you will end up with NumberFormatException

singhakash
  • 7,891
  • 6
  • 31
  • 65
0

You have a String[] and you are doing this:

final String a = "a";
final String b = "b";
final String ab = a + b;
System.out.println(ab); // "ab"

You need to use numbers if you want to carry out numeric operations:

final int a = 8;
final int b = 1;
final int ab = a + b;
System.out.println(ab); // 9

If you want to do this with String you have to convert:

int[] sums = IntStream.range(0, Math.min(a.length, b.length))
        .map(i -> Integer.parseInt(a[i] + Integer.parseInt(b[i])))
        .toArray();

If you want a String[] as a result:

String[] sums = IntStream.range(0, Math.min(a.length, b.length))
        .map(i -> Integer.parseInt(a[i] + Integer.parseInt(b[i])))
        .mapToObj(Integer::toString)
        .toArray(String[]::new);
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

Convert the String to Integer, Then add.

 public static void main(String[] args) {
            String[] a = {"1","2","5","9"};
            String[] b = {"8","6","7","2"};

            System.out.println(Integer.parseInt(a[0])+ Integer.parseInt(b[0]));

        }
Anjula Ranasinghe
  • 584
  • 1
  • 9
  • 24