当前位置: 代码迷 >> java >> 反转整数但得到`StringIndexOutOfBoundsException`
  详细解决方案

反转整数但得到`StringIndexOutOfBoundsException`

热度:45   发布时间:2023-07-17 20:01:04.0

我正在尝试编写一个程序来反转以负号开头的整数。 例如,如果数字为-123 ,则输出应为-321 但是我得到了:

StringIndexOutOfBoundsException: String index out of range: 4

排队:

result += myString.charAt(i) + "";

代码逻辑有什么问题?

public class ReverseInteger {

    public static void main(String[] args){

        int x = -123;
        String myString = Integer.toString(x);
        String result = "";

        if(myString.charAt(0) == '-'){
            char sign = myString.charAt(0);
            for(int i = myString.length(); i > 1; i--){
                result += myString.charAt(i) + "";
            }
            result = sign + "" + result;
        }

        System.out.println(result);
    }
}

在Java中对String或数组进行索引是从零开始的 这意味着索引0是字符串中的第一个字符,而mystring.length() - 1是字符串中的最后一个字符。 mystring.length()在字符串的末尾

由于您正在访问索引为mystring.length()的数组,因此超出了数组的范围,因此是例外。

您想从索引mystring.length() - 1开始循环。 此外,您将希望继续下降到索引1 ,而不是像在循环中那样排除该索引。

像这样:

for (int i = myString.length() - 1; i > 0; i--)

这是因为您正在使用

for(int i = myString.length(); i > 1; i--){
    result += myString.charAt(i) + "";
}

String.length()返回从1到X的长度。0表示空字符串。

您需要添加-1

for(int i = myString.length() - 1; i > 0; i--){
   result += myString.charAt(i) + "";
}

下面的线似乎是问题

result += myString.charAt(i) + "";

更改为:

result += myString.charAt(i-1) + "";