-1

I am trying to write a program to determine the sum of the digits in a string using recursion, I thought that the following code would print "The sum is 6" to the console but instead it outputs "The code is 150".

Could someone please tell me what my mistake is?

public class SumOfString {
public static String Test = new String();
public static Integer count = new Integer(0);
public static Integer sum = new Integer(0); 
public static long sumThis(String s){
    if (count< s.length()){
        if (Character.isDigit(s.charAt(count))){
            int digit = s.charAt(count);
            count++;
            sum += digit;
            return sumThis(s);}
        else{
            count++;
            return sumThis(s);}}
    else{
        return sum;}}
public static void main(String[] args) {
    Test= "1a2b3c";
    System.out.println("The sum is " + sumThis(Test));
}
Wrolly13
  • 21
  • 1
  • 4

3 Answers3

1

Without solving the problem for you:

One bug in your code is :

int digit = s.charAt(count);

Test this snippet of code on the String "1" with a count of 0. It does not return the integer 1. To get that, you need to wrap this call :

Character.getNumericValue(s.charAt(count));

You should really get in the habit of running your code in the debugger.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
1

The cause of this is the line at

int digit = s.charAt(count);,

charAt will return a character primitive therefore it will be the decimal value of that character.

Character = Decimal Value
`1` = 49
`2` = 50
`3` = 51
-------
150

You need to convert the character to int: Java: parse int value from a char

Community
  • 1
  • 1
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
1

Have a look at a ascii table as you will see that the value of "1" is 49, "2" is 50 and "3" is 51 summing to 150

try

int digit = s.charAt(count) - 48;
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64