gpt4 book ai didi

java - 为什么我会收到此异常?字符串索引越界

转载 作者:行者123 更新时间:2023-12-01 16:52:33 25 4
gpt4 key购买 nike

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)

罗马数字的十进制值为:

  1. M = 1000

  2. D = 500

  3. C = 100

  4. L = 50

  5. X = 10

  6. V = 5

  7. I = 1

有人可以帮忙吗?该程序的含义是从用户处获取罗马数字,然后将其转换为十进制值。非常感谢任何输入:)....用 try/catch 包围来处理它处理的异常,而不是输出正确的值....那么为什么我会收到此异常以及如何摆脱它?

最佳答案

这一行是你的问题。

 for(int i=0;i<=roman_NumeralLength;i++)

NumeralLength 将为您提供字符串中的字符数。但是,最大的合法索引始终是 length()-1。

因此,您尝试访问字符串之外的字符,从而导致索引越界,因为索引始终将 0 视为一个位置。

修复。

 for(int i=0;i<=roman_NumeralLength-1;i++)
// Just insert (-1)...Or change the comparator to "<".
//Both give you the same result

关于java - 为什么我会收到此异常?字符串索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com