2014-12-07 20 views
0

我必須製作一個程序,將羅馬數字轉換爲十進制數。我很困惑如何編寫羅馬數字的條件,如IV(4),IX(9),XL(40)和CM(900)。我寫的代碼適用於所有其他數字。羅馬數到Java中的十進制數

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); 
} 

回答

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; 
} 
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