Saturday, March 24, 2012

BlueJ Program On Decimal To Roman Number Conversion


In this BlueJ program user will enter any decimal value greater than 0 but less than 4000 and the equivalent roman number will be displayed.

import java.io.*;
class Name
{
   
      String roman[]  = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    int decimal[]  = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
    int b;
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  
    public void take() throws Exception
{
String str="";
while(true)
{
System.out.println("Enter the decomal number;");
b=Integer.parseInt(br.readLine());
if(b>0 && b<4000)
break;
}
for (int i = 0; i < roman.length; i++) {
            while (b >= decimal[i]) {
                b = b-decimal[i];
                str = str+roman[i];
            }
        }
        System.out.println("Equivalent roman="+str);
    } 
    public static void main(String args[])throws Exception
    {
new Name().take();
}
}
Technical analysis of the decimal to roman number conversion program

Both the decimal numbers having unique roman symbols and the respective roman numbers are stored in two separate arrays. While taking the number from user, it is ensured that the number is more than 0 and at the same time less than 4000. Using the nested loop, the roman numbers are accessed by the outer loop in decending order and the inner loop checks whether the entered value is greater or equal to the equivalent decimanl number. If the number the greater than the equivalent decimanl number, the entered number is reduced by the equivalent decimal and the matching roman number is concatenated on a string object. This process is carried on until all the roman numbers are accessed. Depending upon the entered decimal value, the inner loop will execute but the outer loop continues until all the roman numbers are accessed.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner