import java.io.*;
public class TestStringBuffer01
{
public static void main(String args[])throws IOException
{
BufferedReader buf;
String s1;
buf =new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入字符串:");
s1=buf.readLine();
StringBuffer sb1=new StringBuffer(s1);
StringBuffer sb2=sb1.reverse();
//System.out.println(sb1);
//System.out.println(sb2);
System.out.print("s1是否为回文:"+s1.equals(sb2.toString()));//这里的比较,sb2为什么要加toString啊?因为它是StringBuilder类型吗?
}
}
不是很懂哎!!!求指点......

解决方案 »

  1.   

    先要弄清楚s1为String类型,而sb2是StringBuilder类,首先两个类型就不同。你看一下String的equal方法定义,它会首先判断参数是否为String类型,如果不是String类型就直接返回错误。
      

  2.   

    查看API:equals方法的说明:
    Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. 
    也就是说:将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。
    StringBuilder与String类型都不同,比较的话肯定返回false,所以要先把StringBuilder.toString()转换为String类型比较才有意思!
      

  3.   

    恩恩,学习了现在初学java,以后还有很多不懂的需要请教哈。