Java:charAt转换为int吗? [英] Java: charAt convert to int?

查看:66
本文介绍了Java:charAt转换为int吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输入我的 nirc 号,例如 S1234567I ,然后将 1234567 分别作为整数作为 indiv1 作为 charAt(1) indiv2 表示为 charAt(2) indiv 表示为 charAt(3),依此类推.但是,当我使用下面的代码时,我可以似乎连第一个数字都拿不出来?有什么主意吗?

I would like to key in my nirc number e.g. S1234567I and then put 1234567 individualy as a integer as indiv1 as charAt(1), indiv2 as charAt(2), indiv as charAt(3), etc. However, when I use the code below, I can't seem to get even the first number out? Any idea?

  Scanner console = new Scanner(System.in);
  System.out.println("Enter your NRIC number: ");

  String nric = console.nextLine();

  int indiv1 = nric.charAt(1);
  System.out.println(indiv1);

推荐答案

您将得到49、50、51等-这些是字符"1","2","3"的Unicode代码点等

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

如果知道它们将是西数,则只需减去"0"即可:

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

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

但是,只有在已经在其他地方验证字符串的格式正确之后,才应执行此操作-否则,最终将得到虚假数据-例如,"A"最终将返回17而不是导致错误.

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.

当然,一种选择是获取值,然后检查结果是否在0-9范围内.一种替代方法是使用:

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);

如果字符不是适当的数字,它将返回-1.

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.

这篇关于Java:charAt转换为int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆