我一直在尝试编写代码来检查一个单词是否是第一个字母和最后一个字母相同的单词。本质上,它是检查单词是否是回文的代码。
代码
import java.util.*;
public class Class1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
String n = reader.next();
boolean right = true;
for (int i=0; i<n.length();i++)
{
int f = n.length()-i;
if (n.charAt(i) != n.charAt(f -i))
{
right=false;
}
}
System.out.println("The word is " + right);
}
}
我收到此错误:
TT
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(Unknown Source)
at Class1.main(Class1.java:12)
谢谢。
最佳答案
几乎是正确的,只是int f = n.length()-i;
应该是int f = n.length()-1;
。
n.length()-1
是字符串中最后一个字符的索引。因此 f-i
将是右侧的第 i 个字符。
关于java.lang.StringIndexOutOfBoundsException : String index out of range when trying to check if a word is a palindrome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25473810/