简体   繁体   中英

Can I multiply charAt in Java?

When I try to multiply charAt I received "big" number:

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

Result : 103

But when I want to receive only one number it's OK .

On the JAVA documentation:

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

So I need explanation or solution (I think that I should convert string to int , but it seems to me that is unnesessary work)

char is an integral type . The value of s.charAt(0) in your example is the char version of the number 50 (the character code for '2' ). s.charAt(1) is (char)53 . When you use + on them, they're converted to ints, and you end up with 103 (not 100).

If you're trying to use the numbers 2 and 5 , yes, you'll have to parse them. Or if you know they're standard ASCII-style digits (character codes 48 through 57, inclusive), you can just subtract 48 from them (as 48 is the character code for '0' ). Or better yet, as Peter Lawrey points out elsewhere, use Character.getNumericValue , which handles a broader range of characters.

Yes - you should parse extracted digit or use ASCII chart feature and substract 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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