1
\$\begingroup\$

Yes, I made it up.

This program checks if an entered string is a palindrome or not by assigning a char variable the characters in the inserted word in reverse order. The program then takes the variable and appends it to a StringBuilder to be able to compare the original word and the finalized reversed version.

package Palindrome;

import java.util.Scanner;


public class palindrome {

static String word;
StringBuilder reversedWord = new StringBuilder();

public palindrome() {
    char reversedChar;

    for (int i = 1; i < word.length() + 1; i++) {
        reversedChar = word.charAt(word.length() - i);
        reversedWord.append(reversedChar);
    }
}

public void checkPalindrome() {
    if(word.equalsIgnoreCase(reversedWord.toString())) {
        System.out.println("You got a Palindrome!");
    }else{
        System.out.println("That's not a Palindrome...");
    }
}

public static void main(String[] args) {
    System.out.print("Enter a word to check Palindromness: ");
    Scanner scan = new Scanner(System.in);
    word = scan.next();
    scan.close();
    new palindrome();
    new palindrome().checkPalindrome();
    }
}
\$\endgroup\$
1
\$\begingroup\$

notes:

  1. Your coding style seems good. There is some inconsistent indentation, but i am guessing that is a question formatting problem.

  2. Having a static variable word means that palindrome is not threadsafe, and is confusing to call. either pass word to the palindrome constructor, or make checkPalindrome() a static method that takes a string.

  3. checkPalindrome() outputs it's result to standard output. What if you wanted to make your palindrome checker graphical?. have checkPalindrome() return a boolean indicating whether word is a palindrome or not. This concept of seperating model and output code is extremly important.

  4. Instead of wasting time and memory copy over the string backwards then checking for equality, you can compare pairs of characters starting at both ends of the string.

  5. When you reverse the string, you can write a for loop that goes backwards:

    for (int i = word.length() - 1; i >= 0; --i) {
        reversedChar = word.charAt(i);
        reversedWord.append(reversedChar);
    }
    

example:

public boolean checkPalindrome(String word) {
    for (int i = 0; i < word.length() / 2; ++i) {
        if (Character.toLowerCase(word.charAt(i)) !=
                Character.toLowerCase(word.charAt(word.length()-i-1))) {
            return false;
        }
        return true;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.