gpt4 book ai didi

java - 回文代码(错误如下)

转载 作者:行者123 更新时间:2023-12-01 09:49:24 25 4
gpt4 key购买 nike

package palindrome;
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the word = > ");
String word = input.nextLine();
int flag = 0;
int x = word.length();
int i = 0;
int j = x;
for(; i<=x/2 && j>=x/2; i++,j--)
{
if(word.charAt(i)!=word.charAt(j))
{
flag = 1;
break;
}
}
if(flag==0)
{
System.out.printf("The word '%s' is a palindrome", word);
}
else
System.out.printf("The word '%s' is not a palindrome", word);
}


}

输出尖叫错误:

输入单词=>女士

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at palindrome.Palindrome.main(Palindrome.java:16)

最佳答案

int j = x;

应该是:

int j = x-1;

关于java - 回文代码(错误如下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37703531/

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