hypesystem

RomanNumeralConverter

Feb 6th, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. import java.util.HashMap;
  2.  
  3. /*
  4.  * RomanNumeralConverter converts numbers from the Roman Numeral System to
  5.  * regular base-10 numbers and back again.
  6.  * @author hypesystem
  7.  * @version 2012-02-16
  8.  */
  9. public class RomanNumeralConverter {
  10.     private HashMap<Character,Integer> values;
  11.    
  12.     public RomanNumeralConverter() {
  13.         values = new HashMap<Character,Integer>();
  14.        
  15.         values.put('I',1);
  16.         values.put('V',5);
  17.         values.put('X',10);
  18.         values.put('L',50);
  19.     }
  20.  
  21.     public int fromRoman(String s) {
  22.         int length = s.length();
  23.         int value = 0;
  24.         for(int pos = 0; pos < length; pos++) {
  25.             if(pos < (s.length() - 1) && values.get(s.charAt(pos)) < values.get(s.charAt(pos + 1))) {
  26.                 value += (values.get(s.charAt(pos + 1)) - values.get(s.charAt(pos))); pos++;
  27.             }
  28.             else value += values.get(s.charAt(pos));
  29.         }
  30.         return value;
  31.     }
  32.    
  33.     public static void main(String[] args) {
  34.         RomanNumeralConverter rom = new RomanNumeralConverter();
  35.         rom.test("I");
  36.         rom.test("II");
  37.         rom.test("III");
  38.         rom.test("IV");
  39.         rom.test("V");
  40.         rom.test("VI");
  41.         rom.test("VII");
  42.         rom.test("XVII");
  43.         rom.test("XLIV");
  44.     }
  45.    
  46.     private void test(String s) {
  47.         StdOut.println(s+" "+fromRoman(s));
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment