Search code examples
javanetbeansroman-numerals

Roman number to decimal in Java


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

Solution

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