对于某些课堂作业,我需要创建一个将罗马数字转换为十进制形式的程序。只要没有例如IV或IX的异常字符,我就可以转换得很好。如何检查这些例外情况?我的尝试是将当前字符和下一个字符转换为十进制,然后比较它们,如果下一个(从右到左)较小然后减去它。问题是我从这里得到了界限错误。
我目前的代码是:
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (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!");
我还是初学者,我在这类问题上看到的大部分信息都使用了我根本不理解的高级解决方案。我知道我需要比较角色,但我不知道如何以最终不会超出界限的方式做到这一点。
编辑:解决了!在发布问题后,我被洞察力所震惊,并自己解决了问题。这段代码有效但我很欣赏任何有关如何改进它的见解!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 to decimal form.");
System.out.println("Note: Roman Numerals are I, V, X, L, C, D and M.");
System.out.println("All letters entered will be treated as capitalized.");
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (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!");
答案 0 :(得分:0)
嗯,小数是##.##
,整数是##
,所以您应该将demical
更改为num
。
按照您的操作设置数字,然后在其后面添加一个检查异常字符。但首先要确保它存在:
if(this character is not the first && the previous character is an exception)
adjust the number as necessary
这将避免越界异常。