Roman number to decimal in Java

1.1k Views Asked by At

I have to make a program that converts Roman numbers to decimal. I am confused about how to write the conditions for the Roman numbers, such as IV (4), IX (9), XL (40) and CM(900). The code that I wrote works for all the other numbers.

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

There are 2 best solutions below

0
On BEST ANSWER

You can check the previous digit.

For example, I added the condition that detects 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
On

Define enum like below:

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

And use it like RomanSymbol.I.getValue() which will return 1 and similarly for other.

So if you accept character from user, you can get the values as:

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

And if you have string like IV, then you could calculate on something like for example:

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