Hai*_*vov 22 java int type-conversion char
(我是Java编程的新手)
我有例如:
char x = '9';
Run Code Online (Sandbox Code Playgroud)
我需要得到撇号中的数字,数字9本身.我试着做以下事情,
char x = 9;
int y = (int)(x);
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
那么我该怎么做才能得到撇号中的数字呢?
khe*_*ood 63
ASCII表的排列使得字符'9'的值比值大9 '0'; 字符的值比值大'8'8 '0'; 等等.
所以你可以通过减去得到十进制数字char的int值'0'.
char x = '9';
int y = x - '0'; // gives the int value 9
Run Code Online (Sandbox Code Playgroud)
azr*_*zro 21
我有char '9',它会存储它的ASCII码,所以要获得int值,你有两种方法
char x = '9';
int y = Character.getNumericValue(x); //use a existing function
System.out.println(y + " " + (y + 1)); // 9 10
Run Code Online (Sandbox Code Playgroud)
要么
char x = '9';
int y = x - '0'; // substract '0' code to get the difference
System.out.println(y + " " + (y + 1)); // 9 10
Run Code Online (Sandbox Code Playgroud)
事实上,这也有效:
char x = 9;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
Run Code Online (Sandbox Code Playgroud)
您存储的9代码对应于horizontal tab(您可以在打印时看到String,也可以按照int上面的说明使用它
278*_*184 13
您可以使用Character类中的静态方法从char获取Numeric值.
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
138939 次 |
| 最近记录: |