Java中的罗马数字到十进制

时间:2014-12-07 09:17:59

标签: java netbeans roman-numerals

我必须制作一个将罗马数转换为十进制的程序。我对如何写罗马数字的条件感到困惑,例如IV(4),IX(9),XL(40)和CM(900)。我写的代码适用于所有其他数字。

public static void main(String[] args) {

    System.out.print("Enter a roman numeral: ");
    Scanner in = new Scanner(System.in);
    String Roman = in.next();
    int largo = Roman.length();
    char Roman2[] = new char[largo];
    int Roman3[] = new int[largo];

    for (int i = 0; i < largo; i++) {
        Roman2[i] = Roman.charAt(i);
    }

    for (int i = 0; i < largo; i++) {
        if (Roman2[i] == 'I') {
            Roman3[i] = 1;
        } else if (Roman2[i] == 'V') {
            Roman3[i] = 5;
        } else if (Roman2[i] == 'X') {
            Roman3[i] = 10;
        } else if (Roman2[i] == 'L') {
            Roman3[i] = 50;
        } else if (Roman2[i] == 'C') {
            Roman3[i] = 100;
        } else if (Roman2[i] == 'M') {
            Roman3[i] = 1000;
        }
    }

    int total = 0;

    for (int m = 0; m < Roman3.length; m++) {
        total += Roman3[m];
    }

    System.out.println("The Roman is equal to " + total);
}

2 个答案:

答案 0 :(得分:0)

定义如下的枚举:

public enum RomanSymbol {

  I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
  private final int value;
  private RomanSymbol(final int value) {
       this.value = value;
  }

  public int getValue() {
      return this.value;
  }

  public int calculateIntEquivalent(final int lastArabicNumber, final int totalArabicResult) {
    if (lastArabicNumber > this.value) {
       return totalArabicResult - this.value;
    } else {
      return totalArabicResult + this.value;
    }  
  }
}

并像RomanSymbol.I.getValue()一样使用它,它将返回1,其他类似地返回。

因此,如果您接受来自用户的字符,则可以将值设为:

char symbol = 'I';//lets assume this is what user has entered.
RomanSymbol rSymbol = RomanSymbol.valueOf(String.valueOf(symbol));
int invalue = rSymbol.getValue();

如果你有类似IV的字符串,那么你可以计算类似的东西:

int lastValue = rSymbol.calculateIntEquivalent(intValue, 0);
lastValue = rSymbol.calculateIntEquivalent(intValue, lastValue); //and so on

答案 1 :(得分:0)

您可以查看上一个数字。

例如,我添加了检测IV的条件:

 if (Roman2[i]=='I'){
   Roman3[i]=1;
 } else if (Roman2[i]=='V'){
   Roman3[i]=5;
   if (i>0 && Roman2[i-1]=='I') { // check for IV
     Roman3[i]=4;
     Roman3[i-1]=0;
   }
 } else if (Roman2[i]=='X'){
   Roman3[i]=10;
 } else if (Roman2[i]=='L'){
   Roman3[i]=50;
 } else if (Roman2[i]=='C'){
   Roman3[i]=100;
 } else if (Roman2[i]=='M'){
   Roman3[i]=1000;
 }