Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum Integers written into a String

I used

int num = Integer.parseInt(str)

to written integer values into a string.I need a function that reads these values from given string and calculates their sum.

Example: input - "43 68 9 23 318" output - 461

like image 297
slaviyy Avatar asked Dec 31 '15 09:12

slaviyy


4 Answers

String str = "43 68 9 23 318";
int num = Integer.parseInt(str)

What you are doing is, trying to parse the complete input string at once, that will throw the NumberFormatException. You need to split it first and then perform the sum on each returned String.


Split the input string by whitespace then parse each number and perform the sum.

public static void main(String[] args) {
  String input = "43 68 9 23 318";
  String numbers[] = input.split("\\s+");   // Split the input string.
  int sum = 0;
  for (String number : numbers) {  // loop through all the number in the string array
    Integer n = Integer.parseInt(number);  // parse each number
    sum += n;     // sum the numbers
  }
  System.out.println(sum);  // print the result.
}
like image 155
YoungHobbit Avatar answered Oct 11 '22 14:10

YoungHobbit


In Java 8, using streams

String input = "43 68 9 23 318";
String numbers[] = input.split("\\s+");
int[] nums = Arrays.stream(numbers.substring(1, numbers.length()-1).split(","))
    .map(String::trim).mapToInt(Integer::parseInt).toArray();
int sum = IntStream.of(nums).sum();
System.out.println("The sum is " + sum);
like image 30
Pravat Panda Avatar answered Oct 11 '22 15:10

Pravat Panda


Another Java 8 way:

public void test() {
    String str = "43 68 9 23 318";
    int sum = Pattern.compile(" ")
            .splitAsStream(str)
            .mapToInt(Integer::parseInt)
            .sum();
    System.out.println("sum:" + sum);
}
like image 22
OldCurmudgeon Avatar answered Oct 11 '22 16:10

OldCurmudgeon


You can try following with java-8. Here we first split the String to get String[] with number String (i.e ["43", "68", "9", "23", "318"]) and then with the help of Arrays.stream we can map all those Strings to Integer and we will have IntStream and from that we can get sum of all streamed Integer values.

public class Test {

    public static void main(String[] args) {
        String input = "43 68 9 23 318";
        int sum = Arrays.stream(input.trim().split("\\s+"))
                        .mapToInt(Integer::parseInt)
                        .sum();
        System.out.println(sum);
    }
}    

OUTPUT

461
like image 22
akash Avatar answered Oct 11 '22 16:10

akash