Convert Number to Roman Number Using Java


 

Convert Number to Roman Number Using Java

In this section, you will learn how to convert the number to roman number using Java.

In this section, you will learn how to convert the number to roman number using Java.

Java Convert Number to Roman Numerals

In this section, you will learn how to convert the number to roman number.  To do this, we have created a class named Roman in which we have stored some numbers and their roman numbers and the method convertIntegerToRoman(int n) convert the specified number into roman if the specified number is within the specified range(1-4999). 

Here is the code:

import java.util.*;

class Roman {
int number; 
String romanNumber; 
Roman(int dec, String rom) {
this.number = dec;
this.romanNumber = rom;
}
}
public class NumberToRoman {
public static void main(String[] args) {
NumberToRoman dec=new NumberToRoman ();
System.out.println("Enter Number");
Scanner input=new Scanner(System.in);
int num = input.nextInt();

String roman = dec.convertIntegerToRoman(num);
System.out.println("Roman Number is: "+roman);
}
final static Roman[] table = {
new Roman(1000"M"),
new Roman900"CM"),
new Roman500"D"),
new Roman400"CD"),
new Roman100"C"),
new Roman90"XC"),
new Roman50"L"),
new Roman40"XL"),
new Roman10"X"),
new Roman9"IX"),
new Roman5"V"),
new Roman4"IV"),
new Roman1"I")
};
public static String convertIntegerToRoman(int n) {
if (n >= 5000 || n < 1) {
System.out.println("Numbers must be in range 1-4999");
}
StringBuffer buffer = new StringBuffer(10);
for (Roman rvalue : table) {
while (n >= rvalue.number) {
n -= rvalue.number; 
buffer.append(rvalue.romanNumber)
}
}
return buffer.toString();
}
}

Output:

Enter number
10
Roman Number is: x

Ads