1 Dec 2013

Roman To Decimal conversion in java example code

/* Roman To Decimal conversion in java example code, roman numeral to decimal java program, java program for converting decimal to roman */

public class RomanToDecimal 

{
public static void romanToDecimal(String romanNumber) 

{
    //Initialization
    int decimal = 0;
    int lastNumber = 0;


//operation to be performed on upper cases even if user enters roman values in lower case chars


    String romanNumeral = romanNumber.toUpperCase();
    for (int x = romanNumeral.length() - 1; x >= 0 ; x--) 

    {
        //getting each character to convert
        char convertToDecimal = romanNumeral.charAt(x);


        //choosing a number
        switch (convertToDecimal) {
            case 'M':

                //if char is equals to 'M' then the number is '1000'
                decimal = processDecimal(1000, lastNumber, decimal);
                lastNumber = 1000;
                break;

            case 'D':

                //if char is equals to 'D' then the number is '500'
                decimal = processDecimal(500, lastNumber, decimal);
                lastNumber = 500;
                break;

            case 'C':

                //if char is equals to 'C' then the number is '100'
                decimal = processDecimal(100, lastNumber, decimal);
                lastNumber = 100;
                break;

            case 'L':

                //if char is equals to 'L' then the number is '50'
                decimal = processDecimal(50, lastNumber, decimal);
                lastNumber = 50;
                break;

            case 'X':

                //if char is equals to 'X' then the number is '10'
                decimal = processDecimal(10, lastNumber, decimal);
                lastNumber = 10;
                break;

            case 'V':

                //if char is equals to 'V' then the number is '5'
                decimal = processDecimal(5, lastNumber, decimal);
                lastNumber = 5;
                break;

            case 'I':

                //if char is equals to 'I' then the number is '1'
                decimal = processDecimal(1, lastNumber, decimal);
                lastNumber = 1;
                break;
        }
    }



    //displaying output
    System.out.println("roman number: "+romanNumber+"\ndecimal number: "+decimal);
}

public static int processDecimal(int decimal, int lastNumber, int lastDecimal) 

{
    //processing decimals
    if (lastNumber > decimal) 

    {
        return lastDecimal - decimal;
    } else 

    {
        return lastDecimal + decimal;
    }
}

//main method
public static void main(java.lang.String args[]) 

{
    romanToDecimal("xi");
}
}



Output:

E:\>javac RomanToDecimal.java
E:\>java RomanToDecimal
roman number: xi
decimal number: 11




Roman To Decimal conversion in java example code

0 comments:

Post a Comment