有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java反转整数,但获取`StringIndexOutOfBoundsException`

我正试图写一个程序来反转以负号开始的整数。例如,如果数字为-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);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    下面这一行似乎就是问题所在

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

    将其更改为:

    result += myString.charAt(i-1) + "";
    
  2. # 2 楼答案

    这是因为你正在使用

    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) + "";
    }
    
  3. # 3 楼答案

    在java中对String或数组进行索引是基于零的。这意味着索引0是字符串中的第一个字符,而mystring.length() - 1是字符串中的最后一个字符mystring.length()在字符串的后面

    由于您在索引mystring.length()处访问数组,因此超出了数组的界限,因此出现了异常

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

    就像这样:

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