最简单的改法是public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a hex number: ");String hex = input.next();System.out.print("The decimal number for the hex is: " + Integer.valueOf(hex, 16));}如果你不想用valueOf(h...
java一个16进制转10进制,求查找问题所在。
你的程序我帮你改完了,你看看吧.
完整的程序如下:(改动的地方见注释)
import java.util.Scanner;public class HexToDecimal { public static void main(String[]args){ Scanner input = new Scanner(System.in); System.out.print("Enter a hex number: "); String hex = input.next(); System.out.print("The decimal number for the hex is: "+ hexToDecimal(hex.toUpperCase())); } public static int hexToDecimal(String hex){ int decimalValue = 0; for(int i = 0;i<hex.length();i++){ if(hex.charAt(i)>'9'){//这里改一下 if(hex.charAt(i)>'F' || hex.charAt(i)<65){//这里改一下 return 00000; } else decimalValue =decimalValue+(int) (Math.pow(16, hex.length()-1-i)*(hex.charAt(i)-55)); }else{ decimalValue =decimalValue+(int) (Math.pow(16, hex.length()-1-i)*(Integer.parseInt(hex.charAt(i)+"",10)));//这里改一下 } } return decimalValue; }}运行结果:
Enter a hex number: 2FThe decimal number for the hex is: 47
2014-08-11
最简单的改法是
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex number: ");
String hex = input.next();
System.out.print("The decimal number for the hex is: " + Integer.valueOf(hex, 16));
}
如果你不想用valueOf(hex,16),那么你后面也不该用valueOf(...,10)2014-08-11