Java int type literals convert decimal number to hex number as a string

Question

We would like to prompt the user to enter a decimal number and converts it into a hex number as a string.

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a decimal number: ");
      int decimal = input.nextInt();

      // Convert decimal to hex
      String hex = "";

      //your code here

      System.out.println("The hex number is " + hex);
   }//from   w w  w. j av a 2 s  . c o  m
}



import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a decimal number: ");
      int decimal = input.nextInt();

      // Convert decimal to hex
      String hex = "";

      while (decimal != 0) {
         int hexValue = decimal % 16;

         // Convert a decimal value to a hex digit
         char hexDigit = (hexValue <= 9 && hexValue >= 0) ? (char) (hexValue + '0') : (char) (hexValue - 10 + 'A');

         hex = hexDigit + hex;
         decimal = decimal / 16;
      }

      System.out.println("The hex number is " + hex);
   }
}



PreviousNext

Related