简体   繁体   English

将字符串数组中的值相加

[英]Add the values from an array of strings together

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. 在此示例中,它给我的输出为17,但我需要为1475。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

You can do this by using split on string and get the value at index 1 您可以通过在字符串上使用split并在索引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 通过使用Java-8

int total = Arrays.stream(arr).mapToInt(str->Integer.parseInt(str.split(" ")[1])).sum();
static Integer sumArray( String[] strArr ) {

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

    return sum;

}

You can do it like this. 您可以这样做。

  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); 

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. 然后,只需将所需的元素解析为int并将其添加到总和中即可。

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM