如何在Java中将char转换为int? [英] How can I convert a char to int in Java?

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

问题描述

(我是Java编程的新手)

(I'm new at Java programming)

我有例如:

char x = '9';

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

and I need to get the number in the apostrophes, the digit 9 itself. I tried to do the following,

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

但它不起作用。

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

So what should I do to get the digit in the apostrophes?

推荐答案

碰巧,ascii / unicode值是字符'9''0'的值大9(与其他数字类似)。

As it happens, the ascii/unicode value of the character '9' is nine greater than the value of '0' (similarly for the other digits).

所以你可以使用减法得到十进制数字char的int值。

So you can get the int value of a decimal digit char using subtraction.

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

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

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