0

I would like to take the Roman Numeral value stored in the object and convert it back to integer, long, float, and double values. I really don't know where to start, other than creating the appropriate methods. Can anyone offer some advice?

http://pastebin.com/sqwdhbtu

Thanks!

3 Answers3

1

You don't appear to need a deep copy as your class appears to be immutable.

Your "convert" methods can all return intVal

vitaut
  • 49,672
  • 25
  • 199
  • 336
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Your question seems to be how to convert a roman numeral to integer. In that case all you need is one function to parse the string from left to right and add the result together while looking for smaller numbers that should be subtracted.

class RomanNumeral{
  String roman;

  public RomanNumeral(String roman){
    this.roman = roman;
  }

  public RomanNumeral Clone(){
    return new RomanNumeral(this.roman);
  }

  public int GetValue(){
    int sum = 0;
    int carry = 0;
    for(int i = 0; i< roman.Length;i++)
    {
     if(i<roman.Length-1){
       if(GetRomanValue(roman[i])>GetRomanValue(roman[i+1])){
          sum += GetRomanValue(roman[i]) - carry;
          carry = 0;
       }
     else carry = GetRomanValue(roman[i]);
    }
    else sum += GetRomanValue(roman[i]) - carry;
  }
 }

  int GetRomanValue(char c)
  {
    switch(c){
     case 'I': return 1;
     case 'V': return 5;
     //and so on...
    }
   }
}

Once you have the integer you can cast it to the other numeric types.

JonC
  • 978
  • 2
  • 7
  • 28
  • Thank you, this works, but what if I actually wanted to create a RomanNumeral object and clone it? –  Jul 03 '12 at 14:46
  • @TimeBomb006 Put the parser method in the RomanNumeral class. Then if you need to clone it you just have to copy the string of roman numerals. – JonC Jul 03 '12 at 15:02
1

As Peter pointed out you don't need a deep copy. Regarding the conversion of roman numeral to arabic, see the answers to this question.

Community
  • 1
  • 1
vitaut
  • 49,672
  • 25
  • 199
  • 336