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)
輸出尖叫!嘈雜的字節序列? – Mena
我很想把這個標記爲http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it,但那不是特定的到'StringIndexOutOfBoundsException'... –
如果你的字符串有'x'字符,那麼最後一個字符的索引是'x-1',而不是'x'。 –