0

Why does this code does not work?
str get "abc redder noon" and function should return count Word == palindrome

in this case, I should return 2!;

public static int countPolindroms(String str) {
    int countWords = 0, start = 0, last, i;
    boolean flag = true;

    str=str.toUpperCase();
    for (i = 0; i < str.length(); i++) {
        if (str.charAt(i) == ' ' || i == str.length() - 1) {
            if (i != str.length() - 1)
                last = i - 1;
            else
                last = i;

            for ( ;start < last && flag ; start++, last--) {
                if(str.charAt(start) != str.charAt(last))
                    flag = false;
            }
            if (flag)
                countWords++;
            if (str.charAt(i) == ' ')
                start = i + 1;
        }
    }
    return countWords;
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • If your current output does not match your desired output, and you don't know why then it's time to start debugging. If you're not sure how to go about doing this, then please check out [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). It won't solve your direct problem, but it will give you steps that you can follow that should help you solve it yourself, or even if that is not successful, then at least help you to better isolate your problem so that your question can be more focused and easier to answer. – Hovercraft Full Of Eels Feb 02 '20 at 16:20
  • since `flag` is directly *controlling* the counting, I would start examining what is happening with it – user85421 Feb 02 '20 at 16:49
  • You are making things too complicated! See this! https://code.sololearn.com/cJ9gIrA6Um0d/#java Think in words not characters and it'll make life a whole lot easier! – JGFMK Feb 02 '20 at 17:10

0 Answers0