2012-07-27 106 views
0

當我嘗試繁殖的charAt我收到了「大」數:我可以在Java中增加charAt嗎?

String s = "25999993654"; 
System.out.println(s.charAt(0)+s.charAt(1)); 

結果:103

但是,當我想收到只有一個號碼沒關係。

在Java文檔:

the character at the specified index of this string. The first character is at index 0. 

所以我需要解釋或解決方案(我想,我應該將字符串轉換爲int,但在我看來這是unnesessary工作)

+2

你不是乘以那裏,您要添加。另外,你所說的輸出是「100」實際上是「103」。 – 2012-07-27 11:18:49

回答

12

charintegral type。在你的例子中,s.charAt(0)的值是數字50的char版本('2'的字符代碼)。 s.charAt(1)(char)53。當你使用+時,它們會轉換爲整數,最後會有103(不是100)。

如果你想使用數字25,是的,你必須解析。或者如果你知道它們是標準的ASCII樣式的數字(字符代碼48到57,含),你可以從它們中減去48(因爲48是'0'的字符代碼)。或者更好的是,正如Peter Lawrey在其他地方指出的那樣,使用Character.getNumericValue,它可以處理更廣泛的字符。

+0

+1,我打算回覆這個,但你打敗了我(我對他如何得到100而感到困惑,並沒有足夠的勇氣說它應該是103)。 – 2012-07-27 11:19:52

+0

該死的你快! :) – 2012-07-27 11:20:07

+0

@SnowBlind:大聲笑,在高中時打字。我母親給我的一些最好的建議(當然,她給了我很多好的建議 - 其中很多我都沒有注意)。 – 2012-07-27 11:23:22

0

是 - 你應該分析提取數字或使用ASCII圖表功能和48。減去:

public final class Test { 
    public static void main(String[] a) { 
     String s = "25999993654"; 
     System.out.println(intAt(s, 0) + intAt(s, 1)); 
    } 

    public static int intAt(String s, int index) { 
     return Integer.parseInt(""+s.charAt(index)); 
     //or 
     //return (int) s.charAt(index) - 48; 
    } 
} 
+0

Character.getNumericValue()在這裏可能是一個更好的選擇。 – 2012-07-27 11:40:14

相關問題