我正在检查是否为回文字符串…为什么这总是打印出 “yes”。

huangapple go评论68阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月14日 00:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63872789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定