Change a decimal to binary with stack java

4

Good morning, I am trying to convert decimal to binary, octal and hexadecimal and vise versa, but does not show me the correct values nor could I pass from binary to decimal, any idea?

public static void main(String[] args) {
    Scanner keyb = new Scanner(System.in);
    Stack pila = new Stack();
    int op;
    long n1 = 0;

    System.out.println("Menu de Opciones:");
    System.out.println("1. Convertir un numero decimal a binario.");
    System.out.println("2. Convertir un numero binario a decimal.");
    System.out.println("3. Convertir un numero decimal a octal.");
    System.out.println("4. Convertir un numero octal a decimal.");
    System.out.println("5. Convertir un numero decimal a hexadecimal.");
    System.out.println("6. Convertir un numero hexadecimal a decimal.");
    System.out.println("7. Salir.");
    System.out.print(" ");
    System.out.print("Ingrese la Opcion que requiere: ");
    op = keyb.nextInt();

    switch (op) {

        case 1:
            System.out.print("Ingrese el numero decimal: ");
            n1 = keyb.nextInt();
            long aux = n1;
            long binario;
            while (aux >=0){
                binario = aux%2;
                pila.push(binario);
                aux /= 2;
            }
            while (pila.empty() == false) {
                System.out.print(pila.pop());
            }
            break;
        case 2:

            break;

        case 3:

            break;

        case 4:

            break;
        case 5:

            break;

        case 6:

            break;

        case 7:
            System.out.print("Programa terminado.");
            break;

        default:
            System.out.print("ERROR! /N"
                    + "Opcion incorrecta, intente de nuevo.");

    }

}

Thank you very much!

    
asked by Carlos Andres Montoya C 28.03.2018 в 23:22
source

1 answer

3

Greetings, Carlos.

Responding only to your question about the conversion from decimal to binary, the problem you have is quite simple:

while (aux >=0) {
    binario = aux%2;
    pila.push(binario);
    aux /= 2;
}

Your program does not pass this while , because the value of aux will never be a negative number, at the time of division, the last value is 0, you should simply change the logical operator >= > , in this way, when the aux takes the value of 0, the loop will end and your program will continue, leaving this way:

while (aux > 0) {
    binario = aux%2;
    pila.push(binario);
    aux /= 2;
}

I did a test trying to convert the decimal 50 to binary and here is the result.

The check I got from this online binary calculator

    
answered by 29.03.2018 / 02:37
source