输入:0xA
输出:10
public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String hex = scanner.next(); if( hex == null || hex.equals("") || !hex.substring(0,2).equalsIgnoreCase("0x")){ return; } Map<String,Integer> map = new LinkedHashMap<>(); char ch = 'A'; int n = 10; while(n<16){ map.put(ch+"",n); ch++; n++; } long sum = 0L; String num = hex.substring(2, hex.length()); String gol = new String(); for(int j=num.length()-1; 0<=j; j--){ char temp = num.charAt(j); gol += temp; } for(int i=0; i<gol.length(); i++){ String k = gol.charAt(i)+""; if (map.containsKey(k)) { Integer val = map.get(k); sum += val*Math.pow(16,i); continue; } try{ long l = Long.parseLong(k); sum += l*Math.pow(16,i); }catch (Exception e){ System.out.println("输入有误"); } } System.out.println(sum); }
还有直接用parse*方法更加简单:
public class SixteenToTen { private Scanner scanner = new Scanner(System.in); private String testStr; @Before public void initStr(){ testStr = "0xA1A"; } @Test public void scanner(){ if(testStr == null || testStr.equals("") || !testStr.substring(0,2).equalsIgnoreCase("0x")){ return ; } String num = testStr.substring(2); int numInt = Integer.parseInt(num, 16); System.out.println(numInt); } }