-1

I know it's very puny thing for experts here but I want to check why my palindrome program is not working as expected, it shows as palindrome to every number or string i enter, can you please look into it where the issue is, please. actually i'm trying to create this program on my own and not checking any ready made method for it so asking here. please help. here's my program

import java.util.*;

public class test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the number");
        String k = sc.next();
        int s = k.length()/2;
        boolean b = true;

        while(s>0){
            for (int i = 0; i<=s; i++) {
                if(k.charAt(i)==k.charAt(s)){
                    b = true;
                }
            }
            if (b)
               s--;
            else
               System.out.println("exit");
        }
        if(b)
           System.out.println("palindrome");
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249

2 Answers2

1

s is the midpoint, and you are modifying it in your loop. Also, you never set b to false in any condition. Fixing those two bugs, should give you something like

Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length() / 2;
boolean b = true; // <-- Default to true
for (int i = 0; i <= s; i++) { // <-- Only need one loop.
    if (k.charAt(i) != k.charAt(k.length() - i - 1)) {
        b = false; // <-- Only need to update when it isn't a palindrome.
        break; // <-- terminate the loop.
    }
}
if (b) { // <-- Use braces. Even when optional.
    System.out.println("palindrome");
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You might be better off writing a simple method to do the check and call that method with your input.

Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String str = sc.next();
System.out.printf("'%s' %s%n", str, (isPalindrome(str) ? "is " : "is not ") + "a palindrome.");

For inputs of radar and abcdcbc prints

'radar' is a palindrome.
'abcdcbc' is not a palindrome.

The method

public static boolean isPalindrome(String str) {
    int len = str.length();
    for (int i = 0; i < len / 2; i++) {
        if (str.charAt(i) != str.charAt(len - i - 1)) {
            return false; // return as soon as characters don't match
        }
    }
    // if the program gets this far, the string must be a palindrome
    return true;
}
WJS
  • 36,363
  • 4
  • 24
  • 39