第8章

    技术2022-05-20  48

    import java.util.Scanner;/** *将十进制转换为十六进制 */

    public class Exercise8_9 { public static void main(String[] args){  System.out.println("请输入十进制数字:");  Scanner sc = new Scanner(System.in);  int i = sc.nextInt();  String s = convert_StringBuffer(i);  System.out.println("对应的十六进制数为:" + s); }  //此方法使用StringBuffer把String保存下的十六进制数倒序输出 public static String convert_StringBuffer(int i){  int num;  String s;  StringBuffer sb = new StringBuffer();  while(true){   num = i % 16;   i /= 16;   if(num >= 10){    sb.append(match(num));   }else{    sb.append(num);   }   if(i <= 16){    if(i >= 10){     sb.append(match(i));    }else{     sb.append(i);    }    //把s倒序后赋值给new_s    sb = sb.reverse();    s =sb.toString();    break;   }  }    return s; }  //此方法不使用StringBuffer public static String convert(int i){  String s = "";  String new_s = "";  int num = 0;  //通过取余运算和除法运算,把结果赋值给s  while(true){   num = i % 16;   i /= 16;   if(num >= 10){    s += match(num);   }else{    s += num;   }   if(i <= 16){    if(i >= 10){     s += match(i);    }else{     s += i;    }    //把s倒序后赋值给new_s    for(int j = s.length() - 1; j >= 0; j--){     new_s += s.charAt(j);    }    break;   }  }    return new_s; }  //功能是把10-15的数转化为十六进制的对应数 public static String match(int i){  String s = "";  switch (i){    case 10:    s = "A";    break;    case 11:    s = "B";    break;   case 12:    s = "C";    break;   case 13:    s = "D";    break;   case 14:    s = "E";    break;   case 15:    s = "F";    break;  }  return s; }}


    最新回复(0)