SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Programming Projects
Question:1 | ISBN:9780136091813 | Edition: 2

Question

Write a program that prompts for a number and displays it in Roman numerals.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

 
package chap456;

import java.util.Scanner;
import java.util.TreeMap;

public class ToRoman {

	public static TreeMap<Integer, String> map = new TreeMap<Integer, String>();

	static {

		// put the value and key pairs in such a way that
		// every interger should be covered in roman number
		map.put(1000, "M");
		map.put(900, "CM");
		map.put(500, "D");
		map.put(400, "CD");
		map.put(100, "C");
		map.put(90, "XC");
		map.put(50, "L");
		map.put(40, "XL");
		map.put(10, "X");
		map.put(9, "IX");
		map.put(5, "V");
		map.put(4, "IV");
		map.put(1, "I");

	}

	public static String toRoman(int num) {
		
		// floorkey in treemap returns the greatest key less than or equal to the given key
		int value = map.floorKey(num);
		if (num == value) {
			return map.get(num);
		}
		return map.get(value) + toRoman(num - value);
	}

	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		System.out.println("enter a number: ");
		int number= input.nextInt();
	    String romanNumber = ToRoman.toRoman(number);
		System.out.println("the respective roman number is: " +romanNumber);
		input.close();

	}

}
Output:

enter a number: 
96
the respective roman number is:XCVI

 

0 0

Discussions

Post the discussion to improve the above solution.