nicholas
nicholas

Reputation: 127

Trouble converting roman numerals to arabic format using arrays

This is my code for Arabic to Roman:

public class RomanNumeral
{

    private static int[] arabics = {1000, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    private static String[] romans = {"M","CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    public static String ArabicToRoman(int arabic)
    {
        int placeHolder = 0;
        String roman = "";
        placeHolder = arabic / 1;
      for(int i = 0; arabic > 0; i++)
      {
          placeHolder = arabic / arabics[i];

          for(int y = 1; y <= placeHolder; y++)
          {
              roman = roman + romans[y];
          }
          arabic = arabic % arabics[i];
      }
      return roman;
    }

I'm looking for a way to do the opposite of this, (converting Roman to Arabic) but I can't seem to figure it out. Would love some tips on how to do this using the same arrays.

Upvotes: 0

Views: 110

Answers (1)

Jar3d
Jar3d

Reputation: 116

Maybe something like this:


    private static int[] arabics = {1000, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    private static String[] romans = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
    public static int indexOf(String needle, String[]haystack, int length){
        int i=-1;while(++i<length&&!(""+haystack.charAt(i)).equals(needle));
        return i==length?-1:i;
    }
    public static int RomanToArabic(String roman){
        int len = roman.length();
        int placeHolder[] = new int[len];
        for(int i=0;i<len;i++) placeHolder[i]=0;
        int arabic = 0, k, j=0;
        for(;j<len-1;j++){
            if((k=indexOf(roman.charAt(j)+""+roman.charAt(j+1),romans,13))!=-1) j++;
            else k=indexOf(roman.charAt(j)+"",romans,13);
            arabic += arabics[k];
        }
        if(j==len-1)arabic += arabics[indexOf(roman.charAt(j)+"",romans,13)];
        return arabic;
    }

Upvotes: 1

Related Questions