Java: charAt convert to int?

前端 未结 6 1180
粉色の甜心
粉色の甜心 2020-12-20 14:39

I would like to key in my nirc number e.g. S1234567I and then put 1234567 individualy as a integer as indiv1 as cha

6条回答
  •  醉酒成梦
    2020-12-20 15:15

    You'll be getting 49, 50, 51 etc out - those are the Unicode code points for the characters '1', '2', '3' etc.

    If you know that they'll be Western digits, you can just subtract '0':

    int indiv1 = nric.charAt(1) - '0';
    

    However, you should only do this after you've already validated elsewhere that the string is of the correct format - otherwise you'll end up with spurious data - for example, 'A' would end up returning 17 instead of causing an error.

    Of course, one option is to take the values and then check that the results are in the range 0-9. An alternative is to use:

    int indiv1 = Character.digit(nric.charAt(1), 10);
    

    This will return -1 if the character isn't an appropriate digit.

    I'm not sure if this latter approach will cover non-Western digits - the first certainly won't - but it sounds like that won't be a problem in your case.

提交回复
热议问题