Search code examples
javapalindrome

Palindrome for Integers and Strings Java


I'm trying to create Palindrome app for Integers and Strings in Java, I'm having an issue with my if statement, it outputs incorrect/repeating True and False statements:

import java.util.Scanner;
import java.io.*;

public class Palindrome {
    public static void main(String[] args) {

        Scanner user_input = new Scanner(System.in);

        System.out.println("Enter characters to check for Palindrome: ");



        if ( user_input.hasNextInt() ){
            String intToString = String.valueOf(user_input.nextInt()).toString();
            String reversedInt = new StringBuffer(intToString).reverse().toString();

            for (int i = 0; i<intToString.length(); i++) {
                if (intToString.charAt(i) != reversedInt.charAt(i)) { 
                        System.out.println("False");
                    }

                else {
                        System.out.println("True");
                    }
                }
            }


        else if ( user_input.hasNextLine() ) {
            String user_string = user_input.nextLine().replaceAll(" ", "").toLowerCase();
            StringBuilder user_mutable_string = new StringBuilder(user_string);
            user_mutable_string.reverse();

                if (user_string.equals(user_mutable_string.toString())) {
                    System.out.println("True");
                }

                else {
                    System.out.println("False");
                }   
            }

        else {
            System.out.println("Bonkers!");
        }

    }
}

Solution

  • Your issue is with the for loop, which you don't need. You have already reversed the numbers and converted both the original and reversed numbers to a String. All you need to do then is to compare them. Change the for loop to a simple if:

            if (intToString.equals(reversedInt)) { 
                System.out.println("True");
            }
            else {
                System.out.println("False");
            }