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

Write a program that user enters 4 position hexadecimal number and you output th

ID: 3709136 • Letter: W

Question

Write a program that user enters 4 position hexadecimal number and you output the decimal value along with hexadecimal value. Thus 4A7C would output

“Hexadecimal=4A7C equals decimal 19068”. You can NOT use any Java commands that convert text to numbers.

Pseudocode:

input 4 digit hexadecimal number as string

get each character at each position and calculate decimal number

             4 A 7 C

          4 * 163   +    10*162       +    7*161         +     12* 160

    4=charAt(0)      10= charAt(1)     7= charAt(2)    12=charAt(3)

HINT: Math.pow(16,indexK)    is the same as 16indexK

      output input string as well as decimal value -- see example above.

EXTRA CREDIT – MAKE PROGRAM READ IN HEXADECIMAL NUMBER ANY LENGTH

Explanation / Answer

//Code to copy
//Hexa2Decimal.java
import java.util.Scanner;
public class Hexa2Decimal
{
   public static void main(String[] args) {
       //create an instance of Scanner class
       Scanner scanner=new Scanner(System.in);
       String hexa="";
       int decimal=0;
       System.out.printf("Enter 4digit hexa-decimal:");
       //read 4 digit hexa number
       hexa=scanner.nextLine();

      
      
       //checking if lenght is not 4
       if(hexa.length()<4 || hexa.length()>4)
           System.out.println("***Incorrect Hexa-Decimal***");
       else
       {
           int pow=0;
           //calculate the decimal value of hexa number
           for (int index = hexa.length()-1; index >=0; index--,pow++)
           {
               int value=getDecimal(hexa.charAt(index));
               decimal+=value*(int)(Math.pow(16, pow));
           }
           //print decimal number
           System.out.printf("Decimal : %d",decimal);
       }
      
      
   }

   /*The method getDecimal that takes character and then
   * return the decimal equivalent of hexa letter*/
   private static int getDecimal(char hexachar)
   {
       switch(hexachar) {
       case 'A':
           return 10;
       case 'B':
           return 11;
       case 'C':
           return 12;
       case 'D':
           return 13;
       case 'E':
           return 14;
       case 'F':
           return 15;
       default:
           return hexachar-'0';
       }

   }
}

------------------------------------------------------------

Sample Output:

Enter 4digit hexa-decimal:4A7C
Decimal : 19068

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