繁体   English   中英

我可以在Java中乘以charAt吗?

[英]Can I multiply charAt in 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.

因此,我需要说明或解决方案(我认为我应该将string转换为int,但在我看来这是不必要的工作)

char整数类型 在您的示例中, s.charAt(0)的值是数字50的char版本( '2'的字符代码)。 s.charAt(1)(char)53 当您在它们上使用+时,它们将转换为整数,最终得到103(而不是100)。

如果您尝试使用数字 25 ,是的,则必须解析它们。 或者,如果您知道它们是标准ASCII样式的数字(字符代码48至57,包括端值),则可以从中减去48(因为48是'0'的字符代码)。 甚至更好的是,正如Peter Lawrey在其他地方指出的那样,请使用Character.getNumericValue ,它可以处理更大范围的字符。

是的-您应该解析提取的数字或使用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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM