-3

我写了一个检查回文的代码,但它显示所有输入为回文

class Solution {
public static void main(String[] args) {
  String a = "shubham", reverse="";
  StringBuilder input = new StringBuilder();

  input.append(a);

  System.out.println("Value of a:-"+a);
  System.out.println("Value of b:-"+input.reverse().toString());

  if(a.equals(input.reverse().toString())) {
      System.out.println("Given input is palidrome");
  }
  else {
      System.out.println("Given input is not palidrome");
  }
}

上面的输出是:

a 的值:-shubham
b 的值:-mahbuhs
给定的输入是回文

4

2 回答 2

1

StringBuilder.reverse()是一个有状态的操作,意思input.reverse() == inputtrue. (它只是返回this

因此,当您反转打印它然后再次反转它以进行比较时,它将处于其初始位置。这意味着它将等于a

当您删除打印语句时,它将起作用。或者如果你想打印它,那么只需删除-statementreverse()中的调用:if

if (a.equals(input.toString()) {
于 2020-05-19T08:29:49.270 回答
0

reverse操作适用于对象本身,它不返回修改后的副本

System.out.println("Value of b:-"+input); // shubham
input.reverse();
System.out.println("Value of b:-"+input); // mahbuhs
input.reverse();
System.out.println("Value of b:-"+input); // shubham

String a = "shubham", reverse="";
StringBuilder input = new StringBuilder();
input.append(a);

System.out.println("Value of a:-" + a);
System.out.println("Value of b:-" + input); 
input.reverse();

if(a.equals(input.toString())) {
    System.out.println("Given input is palidrome");
}else {
    System.out.println("Given input is not palidrome");
}
于 2020-05-19T08:32:34.517 回答