Java鍵盤輸入八進位和十六進位__Java

來源:互聯網
上載者:User

今天有同學問我Java怎麼用鍵盤輸入十六進位數轉換成十進位數輸出,我查了一下,發現網上的部分回答不夠清楚,很多人不理解為什麼輸入人後斷行符號就報錯了(代碼無誤)。如下:

public static void main(String argv)throws Exception {        Scanner sc = new Scanner(System.in);        System.out.print("\n請輸入一個16進位數:");        String str = sc.next();        int n = Integer.parseInt(str, 16);        System.out.println("輸入 " + str + ",轉換成整數是  " + n);}
我試著運行了一下這段代碼,輸入0x39,斷行符號,然後報錯了: Exception in thread "main" java.lang.NumberFormatException: For input string: "0x39"(數字格式異常)

查看API後發現,Integer類裡面的靜態方法parseInt(String s, int radix): 這個函數在用Scanner輸入字串的時候,不能有前置0x或者0,後面的radix參數就是指定你輸入的進位類型,例子:

public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String s;int b;s = scanner.nextLine();b = Integer.parseInt(s, 16);System.out.println(b);}

這樣就轉換成功了,切記,輸入的字串一定要和後面的radix相匹配,例如radix = 8,輸入9,八進位中沒有9,所以程式拋出異常。

另外Integer類裡面還提供了一個靜態方法decode(String nm),該函數將String對象解碼為Integer對象返回,這裡的參數nm,需要帶前置,指定代表進位類型。例子:

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);}

                   

本人剛開始試著寫部落格,有什麼錯誤或者描述不當的地方還請大家指出,謝謝大家的查看。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.