Today, there was a problem with the machine test: How to turn char ' 9 ' to int 9, you should know that you can't convert directly, so you get the ASCII of ' 9 '. As below:
public class Intandcharconvertor {public
static void Main (string[] args) {
char NumChar = ' 9 ';
int intnum = (int) NumChar;
System.out.println (NumChar + ":" + Intnum);
}
Run Result:
9:57
So how do you convert char ' 9 ' to int 9?
Method One: First convert char to char[1] array, then convert to string, and finally, using the Parserint method in integer, this method consumes a lot of memory to create multiple objects.
Method Two: Using the encapsulation class character of Char, it can be realized directly through the static method.
public static int Getnumericvalue (CHAR-ch) {return
getnumericvalue (int) ch);
}
Example:
Package Com.albertshao.interview;
public class Intandcharconvertor {public
static void Main (string[] args) {
char NumChar = ' 9 ';
int intnum = (int) NumChar;
System.out.println (NumChar + ":" + intnum);
Method 1:
char[] Chararray = {NumChar};
Intnum = Integer.parseint (new String (Chararray));
System.out.println ("Method 1:" + NumChar + ":" + intnum);
Method 2:
System.out.println ("Method 2:" + NumChar + ":" + character.getnumericvalue (NumChar));
}
Run results
9:57 method
1:9:9 method
2:9:9