0

Heres my code. I'm not sure whats wrong. My project is to create a program that checks if a word is a palindrome.

import java.util.Scanner;

public class PalindromeChecker {
    public static void main(String[] args) {
        // Open Scanner
        Scanner input = new Scanner(System.in);
        // Prompt User for word
        System.out.println("Enter word to check if it is a Palindrome:");
        // Scan in the word
        String word = input.nextLine();
        int a = 0; // used to extract word from array (small)
        int b = 0; // used to extract word from array (large)
        int c = 0; // used to stop when
        int d = (word.length());
        int e = d / 2;
        int f = e - 2;
        int x = word.length(); // set cap of array pulling
        char[] array = word.toCharArray(); // create array of chars
        if (array[a] == array[x] && c != f) {
            a++;
            x--;
            c++;
        } else {
            b = 1;
        }
        if (b == 1) {
            System.out.println("This word is not a Palindrome!");
        } else if (b == 0) {
            System.out.println("This word is a Palindrome!");
        }
    }
}

The error is at the

if (array[a] == array[x] && c!=f)

I'm not exactly sure what went wrong but when you put in a non-palindrome it skips over. I'd be more than glad to have some advice as to what to do in this situation.

3
  • 1
    Would be nice if you named your variables. Commented Jun 22, 2015 at 0:27
  • @schmosel Got it. One sec. Commented Jun 22, 2015 at 0:28
  • Where is the loop you should apply to check array characters? Commented Jun 22, 2015 at 0:40

1 Answer 1

4

Because arrays are 0-based, the index of the last entry is length -1.

int x = word.length() - 1

You are also missing a loop for checking all the characters in a word. And finally, you seem to have a lot of redundant variables. Here's how you could fix your code:

    boolean isPalindrome = true;
    for (int n = 0; n < array.length / 2; n++){
        if (array[n] != array[array.length - n - 1]) {
            isPalindrome = false;
            break;
        }
    }
    if (isPalindrome) {
        System.out.println("This word is a Palindrome!");
    } else {
        System.out.println("This word is not a Palindrome!");
    }
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this. It solved most problems but now when I used racecafr (I got this from a typo) it doesn't work. Do you have any other advice?
You only check the first and the last letter. You should use a loop to check all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.