Convert Number to Roman Letter in Java
In this example, We will show you about, How to Convert Number to Roman Letter in Java. The program has been tested and shared in the post.

RomanNumberConverter.java
package com.dineshkrish.utilities; import java.util.Scanner; import java.util.TreeMap; /** * * @author Dinesh Krishnan * */ public class RomanNumberConverter { // Defining the Map Object private final static TreeMap<Integer, String> romanMap = new TreeMap<Integer, String>(); // Initializing the Map static { romanMap.put(1, "I"); romanMap.put(4, "IV"); romanMap.put(5, "V"); romanMap.put(9, "IX"); romanMap.put(10, "X"); romanMap.put(40, "XL"); romanMap.put(50, "L"); romanMap.put(90, "XC"); romanMap.put(100, "C"); romanMap.put(400, "CD"); romanMap.put(500, "D"); romanMap.put(900, "CM"); romanMap.put(1000, "M"); } public final static String toRoman(int number) { int l = romanMap.floorKey(number); if (number == l) { return romanMap.get(number); } // Recursive Call return romanMap.get(l) + toRoman(number - l); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Which number you want to conver?"); // Get Input from Console int number = scanner.nextInt(); String romanLetter = toRoman(number); // Printing the Result System.out.println(romanLetter); scanner.close(); } }
Output
Which number you want to conver?
27
The 27 coverted to XXVII
References
1. Stackoverflow Discussion
2. java.util API JavaDoc
3. Java TreeMap API JavaDoc
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet