public class reverse
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a new string : ");
String word = sc.nextLine();
StringBuilder s = new StringBuilder();
for (int i = 0; i <= word.length() - 1; i++)
{
char c = word.charAt(word.length() - i - 1);
s.append(c);
}
System.out.println("Reversed String = " + s);
if (word.equals(s))
{
System.out.println("This is a palindrome");
}
else
{
System.out.println("This is not a palindrome");
}
}
}
无论我输入什么字符串作为输入,这总是打印“这不是回文”
答案 0 :(得分:4)
你需要
if (word.equals(s.toString())){
...
}
答案 1 :(得分:2)
单词的类型为String
,s的类型为StringBuilder
,因此它们在类型方面不相同。
应该是
if (word.equals(s.toString()) {
....
}
答案 2 :(得分:1)
在StringBuilder实例上调用toString(),然后与equals方法进行比较
if(s.toString()。equals(word)){
}