Java-字符串索引超出范围

Java-字符串索引超出范围,java,palindrome,Java,Palindrome,由于某种原因导致这个错误,我不知道为什么。它发生在第70行,我有以下代码: if(strNum.charAt(0) == strNum.charAt(strLength)) 以下是整个计划:(同时,我们也非常感谢您提供的清理建议!) 这就是错误: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6 at java.lang.String.charAt

由于某种原因导致这个错误,我不知道为什么。它发生在第70行,我有以下代码:

if(strNum.charAt(0) == strNum.charAt(strLength))
以下是整个计划:(同时,我们也非常感谢您提供的清理建议!)

这就是错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:658)
at LargestPalindromeProduct.isPalindromic(LargestPalindromeProduct.java:70)
at LargestPalindromeProduct.main(LargestPalindromeProduct.java:16)

字符串的合法索引从
0
String.length()-1
,因此
strLength
等于
strNum.length()
,是非法索引

您需要将
strLength
替换为
strLength-1
,将
strLength-1
替换为
strLength-2
,等等。

如果
string.length()
6
这意味着
String
具有索引
0-5
中的字符,因此在
6
处访问它可能导致
ArrayIndexOutOfBoundException

就你而言

int strLength = strNum.length();//Available indexes 0,1,2,3,4
if(strLength == 5) {//Because length is 5

    if(strNum.charAt(0) == strNum.charAt(strLength)) {//Here AIOB
    //Because you are trying this : strNum.charAt(5) which is invalid
换行

if(strNum.charAt(0) == strNum.charAt(strLength-1))
它会起作用的。java中数组的最后一个元素是sizeOfArray-1

如果答案有效,别忘了接受

祝你好运


Iman

字符串需要记住的是它是一个从0到n的字符数组,因此
str.length()
返回的是字符串中的字符数,而不是最后一个位置。获取最后一个元素是使用
str.length()-1

ahhhh我明白了。非常感谢您的快速回复。所以我只需要从每个strLength中减去1。
if(strNum.charAt(0) == strNum.charAt(strLength-1))