今天有同學問我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);}
本人剛開始試著寫部落格,有什麼錯誤或者描述不當的地方還請大家指出,謝謝大家的查看。