Design a class DeciHex to accept a positive integer in decimal number system from the user and display its hexadecimal equivalent.
Example 1:
Decimal number = 25
Hexadecimal equivalent = 19
Example 2:
Decimal number = 28
Hexadecimal equivalent = 1C
Some of the members of the class are given below:
Class name: DeciHex
Data members/instance variables:
num: stores the positive integer
hexa: string to store the hexadecimal equivalent of num
Methods/Member functions:
DeciHex(): constructor to initialize the data members with legal initial values
void getNum(): to accept a positive integer
void convert(int n): to find the hexadecimal equivalent of the formal parameter ‘n’ using the recursive technique
void display(): to display the decimal number and its hexadecimal equivalent by invoking the function convert()
Specify the class DeciHex giving details of the constructor(), void getNum(), void convert(int) and void display(). Define a main() function to create an object and call all the functions accordingly to enable the task.
import java.util.Scanner;
class DeciHex{
int num;
String hexa;
public DeciHex(){
num = 0;
hexa = "";
}
public void getNum(){
Scanner in = new Scanner(System.in);
System.out.print("Decimal number = ");
num = Math.abs(Integer.parseInt(in.nextLine()));
}
public void convert(int n){
if(n == 0)
hexa = "0";
else{
int d = n % 16;
if(d < 10)
hexa = d + hexa;
else{
switch(d){
case 10:
hexa = "A" + hexa;
break;
case 11:
hexa = "B" + hexa;
break;
case 12:
hexa = "C" + hexa;
break;
case 13:
hexa = "D" + hexa;
break;
case 14:
hexa = "E" + hexa;
break;
case 15:
hexa = "F" + hexa;
break;
}
}
if(n / 16 > 0)
convert(n / 16);
}
}
public void display(){
convert(num);
System.out.println("Decimal number = " + num);
System.out.println("Hexadecimal equivalent = " + hexa);
}
public static void main(String[] args){
DeciHex obj = new DeciHex();
obj.getNum();
obj.display();
}
}