62.2k views
0 votes
Write a program that converts a number entered in Roman numerals to decimal. your program should consist of a class, say, Roman. An object of type Roman should do the following:a. Store the number as a Roman numeral.b. convert and store the number into decimal.c. print the number as a Roman numeral or decimal number as requested by the user.the decimal number values of the Roman numerals are:M 1000D 500C 100L 50X 10V 5I 1d. Your class must contain the method romanToDecimal to convert a Roman numeral into its equivalent decimal numbere. Test your program using the following Roman numerals: CXIV, CCCLIX, and MDCLXVI.

User RupertP
by
3.6k points

1 Answer

0 votes

Answer:

The code is given below in Java with appropriate comments

Step-by-step explanation:

import java.util.*;

public class RomantoDecimal {

public static void main(String[] args)

{

Scanner SC = new Scanner(System.in);

RomantoDecimal r = new RomantoDecimal();

System.out.println("Enter a Roman number :");

// INPUT A ROMAN NUMBER

String rNum = SC.next();

// CALL convertToDecimal FOR CONVERSION OF ROMAN TO DECIMAL

r.convertToDecimal(rNum);

}

// M=1000, D=500, C=100, L=50, X=10, V=5, I=1

public void convertToDecimal(String roamNo)

{

int number = 0;

// TEACK EACH DIGIT IN THE GIVEN NUMBER IN REVERSE ORDER

for (int i = roamNo.length() - 1; i >= 0; i--)

{

// FIND OUT WHETHER IT IS 'M' OR NOT

if (roamNo.charAt(i) == 'M')

{

if (i != 0)

{ // CHECK WHETHER THERE IS C BEFORE M

if (roamNo.charAt(i - 1) == 'C')

{

number = number + 900;

i--;

continue;

}

}

number = number + 1000;

}

// FIND OUT WHETHER IT IS 'D' OR NOT

else if (roamNo.charAt(i) == 'D')

{

if (i != 0)

{

// CHECK WHETHER THERE IS C BEFORE D

if (roamNo.charAt(i - 1) == 'C')

{

number = number + 400;

i--;

continue;

}

}

number = number + 500;

}

// FIND OUT WHETHER IT IS 'C' OR NOT

else if (roamNo.charAt(i) == 'C')

{

if (i != 0)

{

if (roamNo.charAt(i - 1) == 'X')

{

number = number + 90;

i--;

continue;

}

}

number = number + 100;

}

else if (roamNo.charAt(i) == 'L')

{

if (i != 0)

{

if (roamNo.charAt(i) == 'X')

{

number = number + 40;

i--;

continue;

}

}

number = number + 50;

}

// FIND OUT WHETHER IT IS 'X' OR NOT

else if (roamNo.charAt(i) == 'X')

{

if (i != 0)

{

if (roamNo.charAt(i - 1) == 'I')

{

number = number + 9;

i--;

continue;

}

}

number = number + 10;

}

// FIND OUT WHETHER IT IS 'V' OR NOT

else if (roamNo.charAt(i) == 'V')

{

if (i != 0)

{

if (roamNo.charAt(i - 1) == 'I')

{

number = number + 4;

i--;

continue;

}

}

number = number + 5;

}

else // FIND OUT WHETHER IT IS 'I' OR NOT

{

number = number + 1;

}

}// end for loop

System.out.println("Roman number: " + roamNo + "\\Its Decimal Equivalent: " + number);

}

}

User Davvs
by
3.6k points