Cem Sultan Cem Sultan - 1 month ago 17
Java Question

Java decToHex in recursive - wrong output order

I tried to check other questions close to this one, but couldn't figure out one answer for mine, that's why sending it as a new post. Hope this won't cause any problem.

I am trying to write a simple JAVA code for number conversion- from decimal to octal or hex. With octal everything is fine, but with hex, the output is in wrong order. like if the answer is 613 - program gives out 316.

Here is my full code:

import java.util.Scanner;

public class Cem {
public static void octalconverter(int a) {
if (a == 0) { //our base
System.out.println(); //I first put here return a, but then it was adding zeros to the end
} else {
System.out.print(a % 8);// first remainder = last digit, and so on
octalconverter(a / 8); //recursively going till it is base
}
}

public static void hexconverter(int a) {

if (a == 0) {
System.out.println();
} else {

System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}

public static String hexchart(int a) {
String result = "";
if (a <= 9) {
result = a + result;
} else {
if (a == 10)
result = result + "A";
// System.out.print("A");
if (a == 11)
result = result + "B";
// System.out.print("B");
if (a == 12)
result = result + "C";
// System.out.print("C");
if (a == 13)
result = result + "D";
//System.out.print("D");
if (a == 14)
result = result + "E";
//System.out.print("E");
if (a == 15)
result = result + "F";
// System.out.print("F");
}
return result;
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner oScan = new Scanner(System.in);
System.out.println("Please enter your decimal number : "); //getting input
int num = oScan.nextInt(); //assigning
System.out.println("Enter 1 for Octal Base Conversion #### Enter 2 for Hex Conversion");
int num2 = oScan.nextInt();

if (num2 == 1) {
System.out.print(num + " in Octal(base8) system is : ");
octalconverter(num); //conversion
} else if (num2 == 2) {
System.out.print(num + " in Hexadecimal(base16) system is : ");
hexconverter(num);
} else {
System.out.println("You entered a wrong choice for conversion type, please restart the program");
}
}
}


Can you please tell me where I messed up. I also must say I am looking for the mistake I did here, not another way of how to write this code. Thank you those who are willing to share another way of it, but again I need to learn my mistake here.
Thank you for your help

Answer

Change

public static void hexconverter(int a) {
    if (a == 0) {
        System.out.println();
    } else {
        System.out.print(hexchart(a % 16));
        hexconverter(a / 16);
    }
}

To

public static void hexconverter(int a) {
    if (a == 0) {
        System.out.println();
    } else {
        hexconverter(a / 16);
        System.out.print(hexchart(a % 16));
    }
}

Your octal conversion is also not working properly. It prints in reverse order. So just swapped those instructions also.