0

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.

Winterone
  • 15
  • 1
  • 1
  • 2
  • You need to convert the string to integer then perform anything you want. Here is a link in stack: http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java – Code Whisperer Feb 27 '15 at 20:43
  • If the conversion is done on the entire string, it's much harder to add individual characters. – krillgar Feb 27 '15 at 20:44
  • possible duplicate of [Java: parse int value from a char](http://stackoverflow.com/questions/4968323/java-parse-int-value-from-a-char) – Emil Laine Feb 27 '15 at 20:45

5 Answers5

2

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.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1
  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);
Nicholas Hirras
  • 2,592
  • 2
  • 21
  • 28
1

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);
}
Omar MEBARKI
  • 647
  • 4
  • 8
1

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);
Code Whisperer
  • 1,041
  • 8
  • 16
0

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));
Saturn
  • 17,888
  • 49
  • 145
  • 271