思路:
还是暴力拆解。
收到后验证是否是16进制数。(空,0x..,长度)
循环取后面两个位并累加,做16转10
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; String binary = "";//2进制字符串 int sumNum = 0;//10进制数值 int len = 0;//16进制字符长度 if((str = br.readLine())!=null){//收到读入数值字符串 if((str.charAt(0)!='0')||(str.charAt(1)!='x'||str.length()>10)){ System.out.println("error input!"); };//十六进制 len = str.length(); for(int i = 0;i < len-2;i++){//将16转2 switch(str.charAt(len-i-1)){ case '0': binary ="0000"+binary; break; case '1': binary ="0001"+binary; break; case '2': binary ="0010"+binary; break; case '3': binary ="0011"+binary; break; case '4': binary ="0100"+binary; break; case '5': binary ="0101"+binary; break; case '6': binary ="0110"+binary; break; case '7': binary ="0111"+binary; break; case '8': binary ="1000"+binary; break; case '9': binary ="1001"+binary; break; case 'A': binary ="1010"+binary; break; case 'B': binary ="1011"+binary; break; case 'C': binary ="1100"+binary; break; case 'D': binary ="1101"+binary; break; case 'E': binary ="1110"+binary; break; case 'F': binary ="1111"+binary; } } int num = 4*(len-2)-1; for(;num >= 0;num--){//按位数累加,2转10 switch(binary.charAt(num)){ case '0': break; case '1': sumNum = sumNum + (int)Math.pow(2,binary.length()-1-num); break; } } } System.out.println(sumNum); } }
错误1:
Main.java:16: error: unclosed character literal
binary = binary + '0000'
^
java中的字符串要用“”,字符是‘’
错误2:
Main.java:13: error: continue outside of loop if((str.charAt(0)=='0')&&(str.charAt(1)=='x')) continue;//十六进制 ^
continue 只能在循环中 用,意思是执行到continue的时候 结束此次循环,进入下一次循环。(原结构不是在循环中使用)
改为了:
if((str.charAt(0)!='0')||(str.charAt(1)!='x')){ System.out.println("error input!"); };//十六进制
错误3:
Main.java:71: error: incompatible types: possible lossy conversion from double to int sumNum = sumNum + Math.pow(2,7-num); ^ 1 error