Today, a classmate asked me how Java keyboard input hexadecimal number to convert to decimal output, I checked, found that the online part of the answer is not clear enough, many people do not understand why the input after the return of the error (code is correct). As follows:
public static void Main (String argv) throws Exception {
Scanner sc = new Scanner (system.in);
System.out.print ("\ n Please enter a 16 number:");
String str = Sc.next ();
int n = integer.parseint (str,);
SYSTEM.OUT.PRINTLN ("input + str +", converted to integer is "+ n");
}
I tried to run this code, input 0x39, enter, and then the error: Exception in thread "main" Java.lang.NumberFormatException:For input string: "0x39" (number format exception)
After viewing the API, we found that the static method parseint (string s, int radix) inside the integer class: This function cannot have a leading 0x or 0 when entering a string with scanner, and the following radix parameter specifies the type of input you entered, example:
public static void Main (string[] args) {
Scanner Scanner = new Scanner (system.in);
String s;
int b;
s = Scanner.nextline ();
B = Integer.parseint (s,);
System.out.println (b);
}
This translates successfully, remember that the input string must match the radix, for example radix = 8, input 9, octal No 9, so the program throws an exception.
Also included in the Integer class is a static method decode (string nm), which decodes a String object back to an integer object, where the parameter nm, which needs to be preceded, specifies a representative type. Example:
public static void Main (string[] args) {
Scanner Scanner = new Scanner (system.in);
String s;
s = Scanner.next ();
Integer A;
A = Integer.decode (s);
System.out.println (a);
}
I just started to try to write blog, what is wrong or improper description of the place also please point out, thank you for your view.