0

I have an array of strings with products and values in it. Laid out like so:

ProductA 200
ProductB 50
ProductC 120
ProductD 1100
ProductE 5

I need to find the sum of all these numbers. The best I have been able to do is use this code to find the sum but it is finding the sum of each individual number:

for (char c : rdmPrize.replaceAll("\\D", "").toCharArray())
{
    int digit = c - '0';
    sum += digit;
    if (digit % 2 == 0)
    {
        evenSum += digit;
    }
}

The output it is giving me in this example would be 17, but I need it to be 1475.

Any ideas?

Thanks!

2
  • It gives you 17, because you are adding digits, not numbers. 2 + 5 + 3 + 2 + 5 = 17, Use Integer.parseInt and then sum numbers. Commented Feb 2, 2019 at 1:45
  • 1
    Use String.split to split each line into 2 tokens, covert the second token to a number and sum it up. Commented Feb 2, 2019 at 1:47

4 Answers 4

2

You can do this by using split on string and get the value at index 1

String[] arr = {"ProductA 200","ProductB 50","ProductC 120","ProductD 1100","ProductE 5"};
    int sum =0;
    for(String s : arr) {
        sum+=Integer.parseInt(s.split(" ")[1]);
    }
    System.out.println(sum);   //1475

By using java-8

int total = Arrays.stream(arr).mapToInt(str->Integer.parseInt(str.split(" ")[1])).sum();
Sign up to request clarification or add additional context in comments.

Comments

0
static Integer sumArray( String[] strArr ) {

    Integer sum = 0;
    for ( String numStr : strArr ) {
        sum += Integer.parseInt( numStr );
    }

    return sum;

}

You can do it like this.

Comments

0
  1. Split strings by spaces
  2. parse the value into a number
  3. Sum

    String[] rdmprice = {
            "ProductA 200", 
            "ProductB 50", 
            "ProductC 120", 
            "ProductD 1100", 
            "ProductE 5"
    };
    
    BigDecimal result = Arrays.stream(rdmprice)
            .map(i -> new BigDecimal(i.split("\\s+")[1]))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    
    System.out.printf("Result: %f", result);
    

Comments

0

Split every input line by space, you will get an array of space separated strings. Then just parse the desired element to int and add it to the sum.

// input[0] = the product name string
// input[1] = the number string

int sum = 0;

for (String[] input : rdmPrize.split(" ")) {
    sum += Integer.parseInt(input[1]);
}

System.out.println(sum);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.