Write a program in Java that converts a number entered in Roman numerals to deci
ID: 3668510 • Letter: W
Question
Write a program in Java that converts a number entered in Roman numerals to decimal. The program should consist of a class, say Roman. An object of type Roman should do the following (which means these are methods in the class):
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 values of the Roman numerals are:
Roman Decimal
M 1000
D 500
C 100
L 50
X 10
V 5
I 1
d. The class must contain the method romanToDecimal to convert a Roman numeral into its equivalent decimal number.
e. Write a TestClient to test the class program using the following Roman numerals. The user enters in: MCXIV, CCCLIX, and MDCLXVI
Explanation / Answer
import java.io.IOException;
import com.esotericsoftware.kryonet.Client;
class Roman numeral
public static int romanConvert(String roman)
{
int decimal = 0;
String romanNumeral = roman.toUpperCase();
for(int x = 0;x<romanNumeral.length();x++)
{
char convertToDecimal = roman.charAt(x);
switch (convertToDecimal)
{
case 'M':
decimal += 1000;
break;
case 'D':
decimal += 500;
break;
case 'C':
decimal += 100;
break;
case 'L':
decimal += 50;
break;
case 'X':
decimal += 10;
break;
case 'V':
decimal += 5;
break;
case 'I':
decimal += 1;
break;
}
}
if (romanNumeral.contains("IV"))
{
decimal-=2;
}
if (romanNumeral.contains("IX"))
{
decimal-=2;
}
if (romanNumeral.contains("XL"))
{
decimal-=10;
}
if (romanNumeral.contains("XC"))
{
decimal-=10;
}
if (romanNumeral.contains("CD"))
{
decimal-=100;
}
if (romanNumeral.contains("CM"))
{
decimal-=100;
}
return decimal;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.