Java keyboard input octal and hexadecimal __java

Source: Internet
Author: User

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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.