从十进制基数转换为十六进制基数

时间:2013-10-21 11:24:15

标签: java

我有一个关于在Java中从十进制基数转换为十六进制基数的问题。我已经完成了部分代码从十进制转换为二进制和八进制,但我有一些十六进制的问题,因为我不知道如何使结果显示与A,B,C,D,E和F.这是我的代码:

package transformare1;
import java.io.*;

public class Transformare1 {


    public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println ("Introduceti un numar natural in baza 10 ");
        int n = Integer.parseInt(br.readLine());
        System.out.println ("Alegeti in ce baza sa fie convertit numarul: 2, 8, 16 ");
        int n1 = Integer.parseInt(br.readLine());
       if (n1==2){
       String b = "";
        while (n!=0){
            int r = (int)(n%2);
            b = r+b;
            n /=2;
        }
        System.out.println ("Numarul binar este "+b);
       }
       else if (n1==8){
       String b = "";
       while (n!=0){
        int r = (int)(n%8);
        b = r+b;
        n /=8;
       }
       System.out.println ("Numarul octal este "+b);
    }
       else if (n1==16){
        String b ="";
        while (n!=0){
        int r = (int)(n%16);
        b = r+b;
        n /=16;
        final char A=10;
        final char B=11;
        final char C=12;
        final char D=13;
        final char E=14;
        final char F=15;
        }
        System.out.println ("Numarul hexadecimal este "+b);   
       }}

}

1 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题。一种方法是使用b = r+b替换代码的“十六进制”部分中的b = "0123456789ABCDEF".charAt(r) + b