gpt4 book ai didi

java - 字符串索引越界异常错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:09 25 4
gpt4 key购买 nike

我不太确定为什么会收到此错误。该代码旨在测试回文,不考虑标点符号。

这是我的代码:

            char junk;
String temp = "";

for (int i = 0; i < txt.length(); i++)
{
junk = txt.charAt(i);
if (Character.isLetterOrDigit(txt.charAt(jumk)))
{
temp += junk;
}
}
txt = temp;
left = 0;
right = txt.length() -1;

while (txt.charAt(left) == txt.charAt(right) && right > left)
{
left++;
right--;
}

java.lang.StringIndexOutOfBoundException : String index out of range 0
at PalindromeTester.main(PalindromeTester.java:35)

第35行如下:

    while (txt.charAt(left) == txt.charAt(right) && right > left)

最佳答案

 if (Character.isLetterOrDigit(txt.charAt(yP)))

是你的问题,yP是一个字符而不是对位置的引用。

您的意思可能是:

 if (Character.isLetterOrDigit(yP))

编辑:我的评论:那么 right 的值将为 -1,而 charAt 需要一个大于 0 的整数。因此您应该检查 txt 的长度,如果它 == 0,则显示一条消息,说明需要一个实际单词。

您应该在到达此行之前停止执行:

right = txt.length() -1;

这是您的固定代码:

do
{
System.out.println("Enter a word, phrase, or sentence (blank line to stop):");
txt = kb.nextLine();
}

while (!txt.equals(""));

txt = txt.toLowerCase();
char yP;
String noP = "";

for (int i = 0; i < txt.length(); i++)
{
yP = txt.charAt(i);
if (Character.isLetterOrDigit(txt.charAt(yP)))
{
noP += yP;
}
}
txt = noP;

left = 0;
right = txt.length() -1;

while (txt.charAt(left) == txt.charAt(right) && right > left)
{
left++;
right--;
}

if (left > right)
{
System.out.println("Palindrome");
cntr++;
}
else
{
System.out.println("Not a palindrome");
}

关于java - 字符串索引越界异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com