如何在 Java 中将 char 转换为 int?

新手上路,请多包涵

(我是 Java 编程新手)

我有例如:

 char x = '9';

我需要得到撇号中的数字,即数字 9 本身。我尝试执行以下操作,

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

但它没有用。

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

原文由 Haim Lvov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 560
2 个回答

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

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

 char x = '9';
int y = x - '0'; // gives the int value 9

原文由 khelwood 发布,翻译遵循 CC BY-SA 4.0 许可协议

我有 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

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String , bu you can also use it as int 正如你在上面看到的

原文由 azro 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题