Wrolly13 Wrolly13 - 1 month ago 6
Java Question

What is my mistake with this code?

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));
}

Answer

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.