Convert Roman numeral to integer. - Java java.lang

Java examples for java.lang:int Format

Description

Convert Roman numeral to integer.

Demo Code

/*   Please see the license information at the end of this file. */
import java.util.*;
import java.util.regex.*;

public class Main{
    /**   Roman numerals to integer map for 1 - 5000 .
     *//*from  w  w w  . j  ava  2s.  co m*/

    protected static Map<String, Integer> romanToIntegerMap = MapFactory
            .createNewMap(5000);
    /**   Convert Roman numeral to integer.
     *
     *   @param   s   The Roman numeral as a string.
     *
     *   @return      The corresponding decimal integer.
     *            -1 if Roman numeral string is bad.
     */

    public static int romanNumeralsToInteger(String s) {
        int result = -1;

        if (s == null)
            return result;

        //   Remove embedded blanks.

        String sFixed = s.toUpperCase().replaceAll(" ", "");

        //   Remove leading and trailing dot.

        int l = sFixed.length();

        if (l > 1) {
            if ((sFixed.charAt(0) == '.') && (sFixed.charAt(l - 1) == '.')) {
                sFixed = sFixed.substring(1, l - 1);
            }
        }
        //   Lookup up Roman numerals string
        //   in map.  If there, return
        //   corresponding integer, else
        //   return -1 .

        Integer i = (Integer) romanToIntegerMap.get(sFixed);

        if (i != null) {
            result = i.intValue();
        }

        return result;
    }
}

Related Tutorials