2012-07-27 46 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

相关问题