‹ Back to the paper
Question 6
10 marks
Computer ScienceISC 2024 Computer Science Paper 1ProgramObjects
Write the program described below.
Design a class DeciHex to accept a positive integer in decimal number system from the user and…
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.
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.
| 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 initialise 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( ) |
Answer
Answer
import java.util.Scanner;
class DeciHex
{
int num;
String hexa;
DeciHex()
{
num = 0;
hexa = "";
}
void getNum()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
num = sc.nextInt();
}
void convert(int n)
{
if (n == 0)
return;
int digit = n % 16;
char ch;
if (digit < 10)
ch = (char) ('0' + digit);
else
ch = (char) ('A' + digit - 10);
convert(n / 16);
hexa = hexa + ch;
}
void display()
{
convert(num);
if (hexa.equals(""))
hexa = "0";
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();
}
}Explanation: The constructor initialises num=0 and hexa="". getNum() reads a positive integer. convert(n) is recursive: it finds the current least-significant hex digit (n%16), recurses on n/16 first (so more significant digits are processed and appended before less significant ones), then appends the current digit's hex character to hexa - this ensures the digits appear in the correct (most-significant-first) order. display() invokes convert(num) and then prints the decimal number and its hexadecimal equivalent. Tested: input 25 gives hexadecimal 19, and input 28 gives hexadecimal 1C, matching both given examples exactly.