java 为什么在运行此程序时会出现“字符串索引超出范围”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26877802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:48:05  来源:igfitidea点击:

Why do I get a "String index out of range" error when I run this program?

java

提问by NEPat10

I am creating a program that converts roman numeral input to it's integer value and every time I run the program I get an error that says,

我正在创建一个程序,将罗马数字输入转换为整数值,每次运行该程序时,我都会收到一个错误消息,

"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(String.java:646)
    at romannumeralconverter.RomanNumeralConverter.convert(RomanNumeralConverter.java:20)
    at romannumeralconverter.RomanNumeralConverter.romanInput(RomanNumeralConverter.java:68)
    at romannumeralconverter.RomanNumeralConverter.printValue(RomanNumeralConverter.java:72)
    at romannumeralconverter.RomanNumeralConverter.main(RomanNumeralConverter.java:77)
Java Result: 1"

Now I am new to programming so I don't know what this means exactly. I am guessing my conversion algorithm is wrong in which the roman numeral entered is not read by the loop. Here is what I have:

现在我是编程新手,所以我不知道这到底是什么意思。我猜我的转换算法是错误的,其中输入的罗马数字没有被循环读取。这是我所拥有的:

public class RomanNumeralConverter {  

public String getUserInput() {

    Scanner numberInput = new Scanner (System.in);
    System.out.print("Enter a roman numeral in uppercase: ");
    String userInput = numberInput.next();
    numberInput.close();
    return userInput;
}

public int convert (String userInput) {
    int result = 0;
    int subtractamount = 0;
    int x = userInput.length();
    while(x != 0) {
    char romanConvert = userInput.charAt(x);
        if(x >= 1) {
        if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
        subtractamount += convertChar(userInput.charAt(x - 1));
    }
}
    result += convertChar(romanConvert);
    x--;

}
result -= subtractamount;
return result;

}

public static char convertChar(char value) {
char result;
switch (value) {
    case 'I':
        result = 1;
        break;
    case 'V':
        result = 5;
        break;
    case 'X':
        result = 10;
        break;
    case 'L':
        result = 50;
        break;
    case 'C':
        result = 100;
        break;
    case 'D':
        result = 500;
        break;
    case 'M':
        result = 1000;
        break;
    default:
        System.out.println("Invalid character!");
        result = 0;
        break;
               }
return result;
}

public int romanInput() {       
    return convert(getUserInput());
}

public void printValue() {
System.out.println(romanInput());
}

public static void main (String[] args) {

new RomanNumeralConverter().printValue();
}
}

If my algorithm is wrong, does anyone know how to fix it?

如果我的算法有问题,有人知道如何解决吗?

回答by Bhesh Gurung

You should start with

你应该从

int x = userInput.length() - 1;

The last character in a string is at the index - (length-of-string - 1), not length-of-string.

字符串中的最后一个字符位于索引 - (length-of-string - 1),而不是 length-of-string。

回答by Ankur Singhal

change userInput.charAt(x);to userInput.charAt(x - 1);

更改userInput.charAt(x);userInput.charAt(x - 1);

charAt starts with index 0 to length -1

or int x = userInput.length() - 1;

或者 int x = userInput.length() - 1;

@nd issue, everything coming out as 0

@nd 问题,一切都为 0

You are actually using uppercase characters in switch statement.

您实际上是在 switch 语句中使用大写字符

so just add below statement,in the starting of your function convert(String userInput)

所以只需在函数的开头添加以下语句 convert(String userInput)

 userInput = userInput.toUpperCase(); // converts user input to uppercase , even if its is already or not.

code

代码

public int convert(String userInput) {
        userInput = userInput.toUpperCase();
        int result = 0;
        int subtractamount = 0;
        int x = userInput.length() - 1;
        while (x != 0) {
            char romanConvert = userInput.charAt(x);
            if (x >= 1) {
                if (convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
                    subtractamount += convertChar(userInput.charAt(x - 1));
                }
            }
            result += convertChar(romanConvert);
            x--;

        }
        result -= subtractamount;
        return result;

    }

output

输出

Enter a roman numeral in uppercase: adig
Invalid character!
Invalid character!
Invalid character!
Invalid character!
501