java - Coverting roman numeral exceptions to decimal -
for class homework need create program converts roman numerals decimal form. can convert fine long there no exception characters such iv or ix. how check these exceptions? attempt translate both current character , next 1 decimal, compare them , if next 1 (going right left) smaller subtract it. problem out of bounds errors this.
my current code this:
scanner keyboard = new scanner(system.in); string roman; int decimal = 0; int number = 0; system.out.print("enter roman numeral convert decimal form: "); roman = keyboard.next(); roman = roman.touppercase(); (int count = roman.length()-1; count >= 0; count--) { char numeral = roman.charat(count); switch (numeral){ case 'i': decimal = 1; break; case 'v': decimal = 5; break; case 'x': decimal = 10; break; case 'l': decimal = 50; break; case 'c': decimal = 100; break; case 'd': decimal = 500; break; case 'm': decimal = 1000; break; default: system.out.println("error: invalid character detected."); break; } number = number + decimal; } system.out.println("the decimal equivalent is: " + number); system.out.println("later!");
i'm still beginner , of information see on kind of problem uses advanced solutions don't understand. know need compare characters i'm not sure how in way won't go out of bounds.
edit: solved! after posting question struck insight , solved problem myself. code works appreciate insights how improve it!
scanner keyboard = new scanner(system.in); string roman; int decimal = 0; int number = 0; int last = 0; system.out.println("this program converts roman numerals decimal form."); system.out.println("note: roman numerals i, v, x, l, c, d , m."); system.out.println("all letters entered treated capitalized."); system.out.print("enter roman numeral convert decimal form: "); roman = keyboard.next(); roman = roman.touppercase(); (int count = roman.length()-1; count >= 0; count--) { char numeral = roman.charat(count); switch (numeral){ case 'i': decimal = 1; break; case 'v': decimal = 5; break; case 'x': decimal = 10; break; case 'l': decimal = 50; break; case 'c': decimal = 100; break; case 'd': decimal = 500; break; case 'm': decimal = 1000; break; default: system.out.println("error: invalid character detected."); system.exit(0); break; } if (decimal >= last){ number = number + decimal; } else { number = number - decimal; } last = decimal; } system.out.println("the decimal equivalent is: " + number); system.out.println("later!");
well, decimal ##.##
, , integer ##
, should change demical
num
.
set number do, , add check after exception character. first ensure exists:
if(this character not first && previous character exception) adjust number necessary
this avoid out-of-bounds exceptions.
Comments
Post a Comment