首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我为什么要得到这个例外?StringIndexOutOfBounds

我为什么要得到这个例外?StringIndexOutOfBounds
EN

Stack Overflow用户
提问于 2016-05-05 04:31:22
回答 4查看 79关注 0票数 0
代码语言:javascript
复制
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();


}

}

这是抛出的错误

代码语言:javascript
复制
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)

罗马数字的十进制值是:

  1. M= 1000
  2. D= 500
  3. C= 100
  4. L= 50
  5. X= 10
  6. V=5
  7. I=1

有人能帮忙吗?这个程序的意思是从用户那里得到一个罗马数字,而不是把它转换成十进制值。任何输入都会受到极大的赞赏:)....surrounded使用try/catch来处理它处理的异常,而不是输出正确的value....so,为什么要得到这个异常,以及如何处理它?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-05-05 04:35:42

这句话是你的问题。

代码语言:javascript
复制
 for(int i=0;i<=roman_NumeralLength;i++)

NumeralLength将给出字符串中的字符数。然而,最大的法律索引总是长度()-1。

因此,您正在尝试访问字符串外的一个字符,从而生成indexOutOfBounds,因为索引总是将0作为一个位置。

敬菲克斯。

代码语言:javascript
复制
 for(int i=0;i<=roman_NumeralLength-1;i++)
 // Just insert (-1)...Or change the comparator to "<".
 //Both give you the same result
票数 2
EN

Stack Overflow用户

发布于 2016-05-05 04:36:12

你要超过你的字符串长度

代码语言:javascript
复制
for(int i=0;i<=roman_NumeralLength;i++) //less than or equals too

应该是

代码语言:javascript
复制
for(int i=0;i<roman_NumeralLength;i++) //less than
票数 1
EN

Stack Overflow用户

发布于 2016-05-05 04:38:37

把等号从你的状态中移除。

代码语言:javascript
复制
for(int i=0;i<roman_NumeralLength;i++)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37042402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档