Java:charAt 转换为 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2627371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:03:21  来源:igfitidea点击:

Java: charAt convert to int?

java

提问by sling

I would like to key in my nircnumber e.g. S1234567Iand then put 1234567individualy as a integer as indiv1as charAt(1), indiv2as charAt(2), indivas charAt(3), etc. However, when I use the code below, I can't seem to get even the first number out? Any idea?

我想输入我的nirc号码,例如S1234567I,然后将1234567个人作为整数作为indiv1as charAt(1)indiv2as charAt(2)indivascharAt(3)等。但是,当我使用下面的代码时,我似乎无法得到第一个数字?任何的想法?

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

采纳答案by Jon Skeet

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

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

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

如果您知道它们将是西方数字,则只需减去 '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.

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

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:

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

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

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

如果字符不是合适的数字,这将返回 -1。

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.

我不确定后一种方法是否会涵盖非西方数字——第一种肯定不会——但听起来这对你来说不是问题。

回答by jonathanasdf

int indiv1 = Integer.parseInt(nric.charAt(1));

int indiv1 = Integer.parseInt(nric.charAt(1));

回答by Roman

try {
   int indiv1 = Integer.parseInt ("" + nric.charAt(1));
   System.out.println(indiv1);
} catch (NumberFormatException npe) {
   handleException (npe);
}

回答by starblue

回答by shareef

I know question is about char to int but this worth mentioning because there is negative in char too ))

我知道问题是关于 char 到 int 的,但这值得一提,因为 char 中也有负数))

From JavaHungry you must note the negative numbers for integer if you dont wana use Character.

如果您不想使用字符,则必须从 JavaHungry 中注意整数的负数。

Converting String to Integer : Pseudo Code

将字符串转换为整数:伪代码

   1.   Start number at 0

   2.   If the first character is '-'
                   Set the negative flag
                   Start scanning with the next character
          For each character in the string  
                   Multiply number by 10
                   Add( digit number - '0' ) to number
            If  negative flag set
                    Negate number
                    Return number

public class StringtoInt {

公共类 StringtoInt {

public static void main (String args[])
{
    String  convertingString="123456";
    System.out.println("String Before Conversion :  "+ convertingString);
    int output=    stringToint( convertingString );
    System.out.println("");
    System.out.println("");
    System.out.println("int value as output "+ output);
    System.out.println("");
}




  public static int stringToint( String str ){
        int i = 0, number = 0;
        boolean isNegative = false;
        int len = str.length();
        if( str.charAt(0) == '-' ){
            isNegative = true;
            i = 1;
        }
        while( i < len ){
            number *= 10;
            number += ( str.charAt(i++) - '0' );
        }
        if( isNegative )
        number = -number;
        return number;
    }   
}