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 Roman( 900, "CM"), new Roman( 500, "D"), new Roman( 400, "CD"), new Roman( 100, "C"), new Roman( 90, "XC"), new Roman( 50, "L"), new Roman( 40, "XL"), new Roman( 10, "X"), new Roman( 9, "IX"), new Roman( 5, "V"), new Roman( 4, "IV"), new Roman( 1, "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 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.