Reputation: 495
I am trying to add Integers inside a list together with one line. The problem is that adding Integers in a string return an object itself and not the sum of the Integers.
For example, I have the string 3 4 6 2 7 4
.
I want to add all of the numbers together like so: 3 + 4 + 6 + 2 + 7 + 4
= 26
. I have tried:
for (String number : after.split ("\\s+")) {
int v = Integer.parseInt (number);
System.out.println (v);
numbers.add (v);
}
Instead of 26, I get [3 4 6 2 7 4]
. How do I get the result of the sum of the integers rather than the Object?
Upvotes: 0
Views: 452
Reputation: 93842
Using Java 8 and streams, you'll be able to do this in one line :
int sum = Arrays.stream("1 2 3".split("\\s+")).mapToInt(Integer::parseInt).sum();
Upvotes: 1
Reputation: 3445
How about this
int sum = 0; //Declare a variable to keep track of your sum
for (String number : after.split ("\\s+")) {
int v = Integer.parseInt (number);
System.out.println (v);
numbers.add(v);
sum += v; //Each iteration of your loop add the current int to your sum
}
System.out.println(sum);
Currently you are just taking each int and adding it to a list. If you want a sum of those values within the list you need another variable to represent this. In my example I have used an int variable named sum. Each time you add an int to your list you will also add it to your current sum value.
Upvotes: 4
Reputation: 121998
Adding to the List is not the same as adding up integer values. You are looking for
numbers +=v;
where numbers in an int value and adding up each value v
in the loop to it.
int numbers =0;
for (String number : after.split ("\\s+")) {
int v = Integer.parseInt (number);
System.out.println (v);
numbers +=v;
}
System.out.println(numbers);
And
numbers +=v;
is a shorthand for numbers = numbers+v
Upvotes: 2
Reputation: 201429
I would use a StringTokenizer like so
public static long add(String in) {
long acc = 0;
StringTokenizer st = new StringTokenizer(in);
while (st.hasMoreTokens()) {
acc += Integer.valueOf(st.nextToken().trim());
}
return acc;
}
public static void main(String args[]) throws IOException {
System.out.println(add("3 4 6 2 7 4"));
}
Which does output 26.
Upvotes: 0