英文:
I am checking for pallindrome string..Why does this always print yes
问题
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
StringBuffer a1 = new StringBuffer();
a1.append(A);
System.out.println(a1.equals(a1.reverse()) ? "Yes" : "No");
}
英文:
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
StringBuffer a1 = new StringBuffer();
a1.append(A);
System.out.println(a1.equals(a1.reverse())?"Yes":"No");
}
答案1
得分: 1
这将始终返回 yes
,因为 a1.reverse()
返回原始的 StringBuffer
对象,它与 a1
相同。如果您想要比较字符串,您需要从 StringBuffer
对象生成字符串:
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
StringBuffer a1 = new StringBuffer();
a1.append(A);
System.out.println(a1.toString().equals(a1.reverse().toString()) ? "Yes" : "No");
}
英文:
This will always return yes
as a1.reverse()
returns original StringBuffer
object which is same as a1
. If you want to compare string, you have to generate string from stringbuffer object:
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
StringBuffer a1 = new StringBuffer();
a1.append(A);
System.out.println(a1.toString().equals(a1.reverse().toString())?"Yes":"No");
}
答案2
得分: 0
是的,通过首先将其转换为字符串,您将能够比较它们。否则,您将比较它们的地址(StringBuffer地址),在这两种情况下都是相同的。
英文:
Yes by converting it into a string first you would be able to compare them .
Otherwise you would be comparing there address(StringBuffer address),which is same is case of both.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论