Re: a way of converting a roman numeral into an integer
[post re-ordered for clarity]
<ljs1987@hotmail.com> wrote in message
news:1167322285.632433.24770@s34g2000cwa.googlegroups.com...
Oliver Wong wrote:
<ljs1987@hotmail.com> wrote in message
news:1167317587.329835.58210@n51g2000cwc.googlegroups.com...
Hi i'm fairly new to java and have been assigned to create a basic
application which converts a roman numeral inputted by a user and then
outputs the corresponding number (integer). Any tips on how to do this
will be much appriciated.
I was thinking of doing an array for each numeral and number but again
i can't really work this out till i figure out how to convert the
numeral into an integer.
Presumably, you mean you want to convert an ASCII representation of
the
roman numerals, so that the 4-character string "VIII" represents 8, as
opposed to using the Unicode single character representation for roman
numeral eight.
Do you know how to use a switch statement?
[...]
static int convertRoman(char c)
{
if (c=='I') return 1;
if (c=='V') return 5;
if (c=='X') return 10;
if (c=='L') return 50;
if (c=='C') return 100;
if (c=='D') return 500;
if (c=='M') return 1000;
return 0;
}
Right, this is pretty much what I intended (although you used an if
statement instead of a switch statement). If you're familiar with
exceptions, it might be a good idea to throw an exception instead of
returning 0 if the input doesn't match any of the predefined letters. If
you're not familiar with exceptions, then don't worry about that for now, as
your code is fine as it is.
The next step is tricky, mainly because the roman numeral system has
some pretty strange rules. Is this for an official school assignment, or are
you just exploring on your own? If the latter, I recommend you pause this
task and try something easier, like converting an integer to its textual
representation. E.g. given the integer 1234, produce the string "one
thousand two hundred thirty four". Once you can do that, come back to this
roman numeral exercise.
- Oliver