Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-越界异常_Java_Indexoutofboundsexception - Fatal编程技术网

Java-越界异常

Java-越界异常,java,indexoutofboundsexception,Java,Indexoutofboundsexception,我收到以下错误:java.lang.StringIndexOutOfBoundsException,我不知道为什么。希望你们当中有人知道解决办法 提前谢谢 static boolean palindromeCheck(String toBeChecked) { String reverse = "", inputWithoutSpaces = ""; for (int i = 0; i < toBeChecked.length(); i++) input

我收到以下错误:
java.lang.StringIndexOutOfBoundsException
,我不知道为什么。希望你们当中有人知道解决办法

提前谢谢

static boolean palindromeCheck(String toBeChecked) {

    String reverse = "", inputWithoutSpaces = "";

    for (int i = 0; i < toBeChecked.length(); i++)
        inputWithoutSpaces += toBeChecked.charAt(i);

    for (int i = inputWithoutSpaces.length(); i > 0; i--) {

        if (inputWithoutSpaces.charAt(i) != ' ')
            reverse += inputWithoutSpaces.charAt(i);

    }

    return (inputWithoutSpaces == reverse) ? true : false;

}
静态布尔回文检查(要检查的字符串){
字符串reverse=“”,inputWithoutSpaces=“”;
对于(int i=0;i0;i--){
if(输入时不带空格。字符(i)!=“”)
反向+=不带空格的输入。字符(i);
}
返回(inputWithoutSpaces==反向)?真:假;
}

charAt()
接受从0到
length()-1的索引,而不是从1到
length()
问题在于:
for(int i=inputWithoutSpaces.length();i>0;i--)

假设
inputWithoutSpaces
的长度为10。i、 e.索引
0
9
。在循环中,从索引
inputWithoutSpaces.length()
开始计数,即
10
。这是不存在的。亨斯是出界的例外


将其更改为
for(int i=inputWithoutSpaces.length()-1;i>=0;i-)
这样您就可以从
9
计数到
0
您的字符串有一个特定的长度(比如长度:5),但是当您想要反向迭代它时,您需要从4开始,一直到0。这意味着您需要更改for循环并使其如下所示:

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