2016-11-15 60 views
-3

這是我的函數,它應該添加並返回字符串中數字的總和。使用charAt總和一個字符串的數字

public static int Sum(int a) { 

    String row = String.valueOf(a); 
    int counter = 0; 
    int sum = 0; 

    while (counter<row.length()){ 
     int b = row.charAt(counter); 
     sum = sum + b; 
     counter++;  
    } 

    return sum; 
} 

我不知道爲什麼這不會添加整數的所有數字。輸出給了我完全不可思議的答案。幫助將不勝感激,歡呼聲。

輸入:8576 輸出:218 預期輸出:8 + 5 + 7 + 6 = 26

修正:

public static int Sum(int a) { 

    String row = String.valueOf(a); 
    int counter = 0; 
    int sum = 0; 

    while (counter<row.length()){ 
     String b = String.valueOf(row.charAt(counter)); 
     int c = Integer.parseInt(b); 
     sum = sum + c; 
     counter++; 

     } 
    return sum; 
} 
+2

當向這些事情尋求幫助時,總是顯示樣本輸入,預期的樣本輸出以及您目前得到的不理解的輸出。 [更多這裏。](/幫助/怎麼問) –

+5

只是因爲「0」!= 0' – AxelH

+0

輸入:8756,1,58,2,0輸出:218,49,109,50,48 – Emolk

回答

1

int b = Row.charAt(i);就是問題所在。整數獲得字符的ascii值。 工作代碼爲:

public static int Sum(int a) { 
     int sum = 0; 
     int rest = 1; 
     while(rest!=0){ 
      rest = a % 10; 
      a = a/10; 
      sum = sum + rest;   
     } 

     return sum; 
    } 

休息總是最後一個數字,因爲INT始終是一個非小數笨並自動四捨五入,你可以可以使用a = a/10;爲「刪除」的最後一位

+1

您的答案存在問題,開始時使用完全不同的解決方案告訴問題出在哪裏和代碼之間存在巨大差異。只要加上'b - ='0'; // 48'本來就夠了。添加一些空格使其更加明顯;) – AxelH

+1

OP已找到代碼... OP的作業已完成;) – AxelH

+0

@AxelH不需要代碼,學習考試:)此方法對於學習其他問題也有幫助這樣對我的考試會有很大幫助! – Emolk

3

的問題是b是數字的Unicode值,¹不是數字值。例如,數字1的Unicode值是49.

要總結數字值,您需要處理該數值。你可以通過使用method Tariq mentions in his answer,將字符轉換爲字符串並將其解析爲int,或使用基於上述Unicode值的數學運算來實現。


¹更迂腐,數字的UTF-16的序列的值,如果該字符可以用單個代碼單元在UTF-16來表示(其數字即可)。在數字(和所有127個ASCII值)的情況下,這與數字的Unicode代碼點相同。

+1

或者使用接收到的原始「int」。 – AxelH

+0

@AxelH:的確,有一種數學方法可以在不使用字符串的情況下得到這個答案。 –

+0

只是一種選擇,你的答案仍然是最好的關於當前的代碼。 – AxelH

2

像上述int b越來越字符的ASCII值,

變化

int b = Row.charAt(i); 

char c = Row.charAt(i); 
int b= Character.getNumericValue(c); 
+0

哦,我忘了'Character.getNumericValue'! –

+0

我不知道這個!真的很好轉換非拉丁數字表示。 – AxelH

+0

是的,Java總是有一些選擇..Thnkx – henrybbosa

0

你實際上是添加字符不是數值的Unicode值。要做到這一點,請看JDK Character類中的這個方法Character#getNumericValue 。您可以更改代碼如下:

public static int sum(int a) { 
    String Row = String.valueOf(a); 
    int counter = 0; 
    int sum = 0; 

    while (counter < Row.length()) { 
     int b = Character.getNumericValue(Row.charAt(counter)); 
     sum = sum + b; 
     counter++; 
    } 
    return sum; 
} 

也可以通過手動執行此操作。而不是這int b = Character.getNumericValue(Row.charAt(counter));行,你可以做int b = Row.charAt(counter) - '0';這就像是如果你有字符1和Unicode的值是49和Unicode值0是48.當你用1字符值與0減去那麼你會得到char 1的實際數值。

相關問題