Reputation: 15
I need to add certain parts of the numerical string.
for example like.
036000291453
I want to add the numbers in the odd numbered position so like
0+6+0+2+1+5 and have that equal 14.
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them. Thanks for your help.
Upvotes: 0
Views: 21675
Reputation: 1041
Below code loops through any number that is a String and prints out the sum of the odd numbers at the end
String number = "036000291453";
int sum = 0;
for (int i = 0; i < number.length(); i += 2) {
sum += Character.getNumericValue(number.charAt(i));
}
System.out.println("The sum of odd integers in this number is: " + sum);
Upvotes: 1
Reputation: 647
You can use Character.digit() method
public static void main(String[] args) {
String s = "036000291453";
int value = Character.digit(s.charAt(1), 10);
System.out.println(value);
}
Upvotes: 1
Reputation: 2596
String s = "036000291453";
int total = 0;
for(int i=0; i<s.length(); i+=2) {
total = total + Character.getNumericValue(s.charAt(i));
}
System.out.println(total);
Upvotes: 1
Reputation: 42858
Use charAt
to get to get the char
(ASCII) value, and then transform it into the corresponding int
value with charAt(i) - '0'
. '0'
will become 0
, '1'
will become 1
, etc.
Note that this will also transform characters that are not numbers without giving you any errors, thus Character.getNumericValue(charAt(i))
should be a safer alternative.
Upvotes: 2
Reputation: 18149
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them.
Character.getNumericValue(string.charAt(0));
Upvotes: 0