import java.util.Scanner;
public class romanNumeral {
public String roman_Numeral;
public int roman_NumeralLength, decimalValue = 0;
public romanNumeral()
{
retrieveInput();
loopThroughString();
System.out.println(decimalValue);
}
public void retrieveInput()
{
Scanner console = new Scanner(System.in);
System.out.print("Enter roman numeral: \n");
roman_Numeral = console.next();
roman_Numeral = roman_Numeral.toUpperCase();
roman_NumeralLength = roman_Numeral.length();
}
public void loopThroughString()
{
for(int i=0;i<=roman_NumeralLength;i++)
{
if(roman_Numeral.charAt(i) == 'M')
decimalValue+=1000;
else if(roman_Numeral.charAt(i) == 'D')
decimalValue+=500;
else if(roman_Numeral.charAt(i) == 'C')
decimalValue+=100;
else if(roman_Numeral.charAt(i) == 'L')
decimalValue+=50;
else if(roman_Numeral.charAt(i) == 'X')
decimalValue+=10;
else if(roman_Numeral.charAt(i) == 'V')
decimalValue+=5;
else if(roman_Numeral.charAt(i) == 'I')
decimalValue+=1;
}
}
public static void main(String[] args) {
romanNumeral program = new romanNumeral();
}
}这是抛出的错误
Enter roman numeral:
M
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at romanNumeral.loopThroughString(romanNumeral.java:25)
at romanNumeral.<init>(romanNumeral.java:9)
at romanNumeral.main(romanNumeral.java:46)罗马数字的十进制值是:
有人能帮忙吗?这个程序的意思是从用户那里得到一个罗马数字,而不是把它转换成十进制值。任何输入都会受到极大的赞赏:)....surrounded使用try/catch来处理它处理的异常,而不是输出正确的value....so,为什么要得到这个异常,以及如何处理它?
发布于 2016-05-05 04:35:42
这句话是你的问题。
for(int i=0;i<=roman_NumeralLength;i++)NumeralLength将给出字符串中的字符数。然而,最大的法律索引总是长度()-1。
因此,您正在尝试访问字符串外的一个字符,从而生成indexOutOfBounds,因为索引总是将0作为一个位置。
敬菲克斯。
for(int i=0;i<=roman_NumeralLength-1;i++)
// Just insert (-1)...Or change the comparator to "<".
//Both give you the same result发布于 2016-05-05 04:36:12
你要超过你的字符串长度
for(int i=0;i<=roman_NumeralLength;i++) //less than or equals too应该是
for(int i=0;i<roman_NumeralLength;i++) //less than发布于 2016-05-05 04:38:37
把等号从你的状态中移除。
for(int i=0;i<roman_NumeralLength;i++)https://stackoverflow.com/questions/37042402
复制相似问题