2016-11-07 172 views
-1

我想編寫一個程序來確定使用遞歸字符串中的數字的總和,我認爲下面的代碼將打印「總和爲6」到控制檯,而是它輸出「代碼是150」。這段代碼的錯誤是什麼?

有人能告訴我我的錯誤是什麼嗎?

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

是什麼'tstInt' – Mritunjay

+0

一個錯誤,應該算是 – Wrolly13

回答

1

沒有解決你的問題:

在你的代碼

一個錯誤是:

int digit = s.charAt(count); 

試驗這個片段對字符串「1」代碼爲0的計數中,不會返回整數1.要得到這個,你需要打包這個調用:

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

你應該真的習慣於o f在調試器中運行你的代碼。

+0

謝謝,我不認爲這會造成問題。 – Wrolly13

1

這種情況的原因是在

int digit = s.charAt(count);行,

charAt將返回原始因此這將是字符的十進制值的一個字符。

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

您需要的字符轉換爲int:Java: parse int value from a char

+0

謝謝,我會盡力記住這一點。 – Wrolly13

1

看一看一個ASCII表,你會看到的"1"值是49,"2"是50和"3"是51求和到150

嘗試

int digit = s.charAt(count) - 48;