Write a method called toRoman that accepts an integer betwee
Write a method called toRoman that accepts an integer between 1 and 3,999 and returns its Roman numeral expression. The letters are:
I for 1
V for 5
X for 10
L for 50
C for 100
D for 500
M for 1000
If the input number is out of range, the method should return the empty String.
Solution
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg;
import java.util.Scanner;
import java.util.TreeMap;
public class Roman {
public static String toRoman(int number)
{
String res = \"\";
if(number<1 || number>3999)
return res;
TreeMap numberToRoman = new TreeMap();
numberToRoman.put(1000, \"M\");
numberToRoman.put(900, \"CM\");
numberToRoman.put(500, \"D\");
numberToRoman.put(400, \"CD\");
numberToRoman.put(100, \"C\");
numberToRoman.put(90, \"XC\");
numberToRoman.put(50, \"L\");
numberToRoman.put(40, \"XL\");
numberToRoman.put(10, \"X\");
numberToRoman.put(9, \"IX\");
numberToRoman.put(5, \"V\");
numberToRoman.put(4, \"IV\");
numberToRoman.put(1, \"I\");
int highestClosestNumber = (int) numberToRoman.floorKey(number);
if(highestClosestNumber == number)
{
res = (String) numberToRoman.get(number);
}
else
{
res = res+numberToRoman.get(highestClosestNumber)+toRoman(number-highestClosestNumber);
}
return res;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println(\"Input a number in 1 to 3999 range : \");
int number = input.nextInt();
String romanEquivalent = toRoman(number);
System.out.println(\"Roman equivalent of number : \"+number + \" is : \"+romanEquivalent);
}
}
OUTPUT:
run:
Input a number in 1 to 3999 range :
98
Roman equivalent of number : 98 is : XCVIII
BUILD SUCCESSFUL (total time: 1 second)

