gpt4 book ai didi

java - 如何使用 .equals() 方法比较两个 StringBuffer 对象?

转载 作者:行者123 更新时间:2023-12-01 06:29:44 27 4
gpt4 key购买 nike

以下代码不起作用。谁能告诉我下面的代码有什么问题。从逻辑上讲它应该有效...

package assignments;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IsPalindrome {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter a Word:");
StringBuffer sb1 = new StringBuffer(br.readLine());
StringBuffer sb2 = new StringBuffer(sb1);
sb1.reverse();

if(sb2.equals(sb1))
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
}
}

最佳答案

尝试

sb1.toString().equals(sb2.toString());

因为StringBuffer#toString方法返回缓冲区内存储的数据的字符串值:

Returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.

关于java - 如何使用 .equals() 方法比较两个 StringBuffer 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17110518/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com