Java第十二章練習習題

司馬文謙發表於2017-11-13

12.6

package practice;

import java.util.Scanner;

public class practice12_6 {

public static void main(String[] args) {

// TODO Auto-generated method stub
Scanner input =new Scanner(System.in);
System.out.println("Enter a hex number");
String hex=input.nextLine();
if(hexToDecimal(hex.toUpperCase())!='f'){
System.out.println("The decimal value for hex number "+hex+" is "+hexToDecimal(hex.toUpperCase()));
}else System.out.println("NumberFormatException");
}
public static int hexToDecimal(String hex) {
int decimalValue=0;
for(int i=0;i<hex.length();i++) {
char hexChar=hex.charAt(i);
if (hexCharToDecimal(hexChar)!=-1) {
decimalValue=decimalValue*16+hexCharToDecimal(hexChar);
}
else {
decimalValue='f';
break;
}
}
return decimalValue;
}
public static int hexCharToDecimal(char ch) {
if(ch>='A'&&ch<='F')
return 10+ch-'A';
else if(ch>='0'&&ch<='9')
return ch-'0';
else 
return -1;
}
}

相關文章