Reputation: 1
Given a delimiter String
as input, add all the numbers together.
For example:
addNumbers("12 24 36") -> 72
addNumbers("12 12 100") -> 124
I am getting number format exception when i try this.
String a="12 34 4 676";
String b=a.replaceAll(" ", "+");
long num=Long.parseLong(a);
Upvotes: 0
Views: 298
Reputation: 61128
Yes, because 12+34+4+676
is not a number, it's an expression.
In Java 8 you could do something like:
final int sum = Stream.of(a.split("\\s")).
mapToInt(Integer::parseInt).
sum();
In Java 7 you could do:
int sum = 0;
for (final String s : a.split("\\s")) {
sum += Integer.parseInt(s);
}
OP's comment: i dont want to use array.
I like a challenge, so here is a solution that uses a Scanner
:
final Scanner scanner = new Scanner(a);
int sum = 0;
while(scanner.hasNextInt()) {
sum += scanner.nextInt();
}
Upvotes: 4
Reputation: 4176
You cannot parse a string that contains operators to directly get the value. Split it using split("\\s")
and then loop through the array and find the sum.
Upvotes: 0