0

Hi I'm trying to build a palindrome but it seem to be not working, please could you help. I'm expected to catch true on dad and false on other things

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter Your User Name");
    String userInput =input.nextLine();
    System.out.println(abcDEF(userInput));
}
static boolean abcDEF(String userInput) {
    StringBuilder s1 = filter(userInput);
    StringBuilder s2 = reverse(userInput);
    return s1.toString() == s2.toString();
}
static StringBuilder filter(String userInput) {
    StringBuilder sb = new StringBuilder();
    char[] inputData = userInput.toCharArray();

    for (int i = 0; i < userInput.length(); i++) {
        if (userInput.matches("[a-zA-Z0-9]+")) {
            sb.append(inputData[i]);
        }
    }
    return sb;
}

static StringBuilder reverse(String userInput) {
    StringBuilder sb = filter(userInput);
    sb.reverse();
    return sb;
}
Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
  • The `filter` method is flawed, too. It is testing the whole string (`userInput.matches`) for every single character. Effectively, this method completely negates (will return an empty string) any string that contains a non-alphanumeric character instead of removing only that one character. – Izruo Jul 28 '19 at 09:47
  • @Izruo this is not duplicate for "How to compare string", rather this is a question on algorithms. – Ashvin Sharma Jul 28 '19 at 10:05
  • @rebin47 I can suggest you a better algorithm so maybe ask another question? – Ashvin Sharma Jul 28 '19 at 10:05
  • @AshvinSharma I am aware that there is a more effective alternative of detecting palindromes, which does not need to compare strings. Nevertheless, the methodology in this question is perfectly valid, but its implementation is flawed. Therefore I only refer to implementation errors, as that is the *scope* of this post. – Izruo Jul 28 '19 at 10:11

1 Answers1

0

change your abcDEF() to this(last line):

static boolean abcDEF(String userInput) {
    StringBuilder s1 = filter(userInput);
    StringBuilder s2 = reverse(userInput);
    return s1.toString().equals(s2.toString());
}

You are comparing the references of two strings in your code, which is not same in your case. Rather, you should compare the content of the strings. And this is how String contents are compared.

Mukit09
  • 2,956
  • 3
  • 24
  • 44