Mercurial > repos > timpalpant > java_genomics_toolkit
comparison src/edu/unc/utils/RomanNumeral.java @ 2:e16016635b2a
Uploaded
| author | timpalpant |
|---|---|
| date | Mon, 13 Feb 2012 22:12:06 -0500 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 1:a54db233ee3d | 2:e16016635b2a |
|---|---|
| 1 package edu.unc.utils; | |
| 2 | |
| 3 // Rudimentary Class for doing Arabic Integer -> Roman Numeral conversion | |
| 4 // Adapted by Timothy Palpant | |
| 5 // File : gui/componenents/calculators/Roman.java | |
| 6 // Description: A static method for converting binary integers to Roman numbers. | |
| 7 // Illustrates: Static inner value class, StringBuffer, throw exceptions. | |
| 8 // Author : Fred Swartz - 2006-12-29 - Placed in public domain. | |
| 9 public class RomanNumeral { | |
| 10 | |
| 11 // This could be alternatively be done with parallel arrays. | |
| 12 // Another alternative would be Pair<Integer, String> | |
| 13 final static RomanValue[] ROMAN_VALUE_TABLE = { | |
| 14 new RomanValue(1000, "M"), | |
| 15 new RomanValue( 900, "CM"), | |
| 16 new RomanValue( 500, "D"), | |
| 17 new RomanValue( 400, "CD"), | |
| 18 new RomanValue( 100, "C"), | |
| 19 new RomanValue( 90, "XC"), | |
| 20 new RomanValue( 50, "L"), | |
| 21 new RomanValue( 40, "XL"), | |
| 22 new RomanValue( 10, "X"), | |
| 23 new RomanValue( 9, "IX"), | |
| 24 new RomanValue( 5, "V"), | |
| 25 new RomanValue( 4, "IV"), | |
| 26 new RomanValue( 1, "I") | |
| 27 }; | |
| 28 | |
| 29 public static String int2roman(int n) { | |
| 30 if (n >= 4000 || n < 1) { | |
| 31 throw new NumberFormatException("Numbers must be in range 1-3999"); | |
| 32 } | |
| 33 StringBuilder result = new StringBuilder(10); | |
| 34 | |
| 35 //... Start with largest value, and work toward smallest. | |
| 36 for (RomanValue equiv : ROMAN_VALUE_TABLE) { | |
| 37 //... Remove as many of this value as possible (maybe none). | |
| 38 while (n >= equiv.intVal) { | |
| 39 n -= equiv.intVal; // Subtract value. | |
| 40 result.append(equiv.romVal); // Add roman equivalent. | |
| 41 } | |
| 42 } | |
| 43 return result.toString(); | |
| 44 } | |
| 45 | |
| 46 private static class RomanValue { | |
| 47 //... No need to make this fields private because they are | |
| 48 // used only in this private value class. | |
| 49 int intVal; // Integer value. | |
| 50 String romVal; // Equivalent roman numeral. | |
| 51 | |
| 52 RomanValue(int dec, String rom) { | |
| 53 this.intVal = dec; | |
| 54 this.romVal = rom; | |
| 55 } | |
| 56 } | |
| 57 } |
