有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中将字符转换为int?

(我是Java编程新手)

例如,我有:

char x = '9';

我需要得到撇号中的数字,数字9本身。 我试着做了以下几件事

char x = 9;
int y = (int)(x);

但它不起作用

那么我应该怎么做才能得到撇号中的数字呢


共 (4) 个答案

  1. # 1 楼答案

    您可以使用Character类中的静态方法从char中获取数值

    char x = '9';
    
    if (Character.isDigit(x)) { // Determines if the specified character is a digit.
        int y = Character.getNumericValue(x); //Returns the int value that the 
                                              //specified Unicode character represents.
        System.out.println(y);
    }
    
  2. # 2 楼答案

    ASCII表的排列使得字符'9'的值比'0'的值大九;字符'8'的值比'0'的值大八;等等

    因此,您可以通过减去'0'得到十进制数字字符的int值

    char x = '9';
    int y = x - '0'; // gives the int value 9
    
  3. # 3 楼答案

    如果您想要获取字符的ASCII值,或者只是将其转换为int,则需要从char转换为int

    什么是演员?强制转换是当我们显式地从一个primitve数据类型或一个类转换到另一个时。这里有一个简单的例子

    public class char_to_int
    {
      public static void main(String args[])
      {
           char myChar = 'a';
           int  i = (int) myChar; // cast from a char to an int
           System.out.println ("ASCII value - " + i);
      }
    

    在本例中,我们有一个字符('a'),并将其转换为整数。打印出这个整数将得到ASCII值“a”

  4. # 4 楼答案

    如果您有char '9',它将存储其ASCII代码,因此要获取int值,您有两种方法

    char x = '9';
    int y = Character.getNumericValue(x);   //use a existing function
    System.out.println(y + " " + (y + 1));  // 9  10
    

    char x = '9';
    int y = x - '0';                        // substract '0' code to get the difference
    System.out.println(y + " " + (y + 1));  // 9  10
    

    事实上,这也是有效的:

    char x = 9;
    System.out.println(">" + x + "<");     //>  < prints a horizontal tab
    int y = (int) x;
    System.out.println(y + " " + (y + 1)); //9 10
    

    您存储9代码,它对应于一个horizontal tab(您可以在打印时看到String,但您也可以在上面看到的int中使用它