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--)