Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program to convert from decimal to Hexadecimal. Cannot use Integer.toHex

ID: 3550588 • Letter: W

Question

Write a program to convert from decimal to Hexadecimal. Cannot use Integer.toHexString(in). Program also has to check if decimal entered is possitive.This is what I have so far. Cannot figure out what I am doing wrong. When I enter 25 result comes out as 1 which is not wright.



import java.lang.*;
import java.util.Scanner;

public class FindHexString {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String hex = "";
        int decimal = 0;
        int remainder = 0;
        int quotient = 0;

        System.out.print("Enter a number to be converted: ");
        decimal = input.nextInt();

        while (decimal > 16) {
            quotient = decimal / 16;
            remainder = decimal % 16;
            
            do {
                remainder = decimal % 16;
            if (remainder == 10) {
                hex = "A" + hex;

            }
            if (remainder == 11) {
                hex = "B" + hex;

            }
            if (remainder == 12) {
                hex = "C" + hex;

            }
            if (remainder == 13) {
                hex = "D" + hex;

            }
            if (remainder == 14) {
                hex = "E" + hex;

            } else if (remainder == 15) {
                hex = "F" + hex;
            }
            
              
            } while (decimal < 16);
            decimal--;
        }
        System.out.print("Your number in hexadecimal is: " + hex + quotient);
    }
}

Explanation / Answer

public class DecToHex {


public static void main(String[] args) {

System.out.println(decToHex(25));

}

public static String decToHex(int in){

String digits = "0123456789ABCDEF";

String result = "";

while(in>0){

result = digits.charAt(in%16) + result;

in /= 16;

}

return result;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote