Question

I'm making a really simple app in java code, but for some reason it doesnt work. its a palindrome checker.

here is the code.

MAIN:

public class main { public static void main(String[] args) { Palindroom.palindroomChecker("RACECAR"); } }

`Palindroom class:

public class Palindroom {

public static void palindroomChecker(String input) {
    String omgekeerd = "";
    boolean isPalindroom = false;
    int length = input.length();
    for(int i = 0; i < length; i++ ) {
        String hulp = "" + input.charAt(i);
        omgekeerd = omgekeerd + hulp;
    }
    System.out.println(omgekeerd);
    System.out.println(input);
    if(omgekeerd.equals(input)){
        System.out.println("DIT IS EEN PALINDROOM!");
    }
    else {
        System.out.println("HELAAS, DIT IS GEEN PALINDROOM!");
    }
}

}`

For some reason the check in the if-statement doesnt go as it has to go. As you can see i checked omgekeerd and input and i also checked earlier the length of omgekeerd to see if there were clear spaces.

Can someone help me out!

thanks in advance

greetings Mauro Palsgraaf

Was it helpful?

Solution 2

You are not actually reversing the string, looks like omgekeerd will be in the same order as input.

Replace for with for(int i = length-1; i >= 0; i--) {

OTHER TIPS

Your logic is flawed. You're reconstructing a new string by appending every char of the input, in the same order, and then check that both strings are equal. So your method always says that the input is a palindrome.

You should construct a new string by appending the chars in the reverse order.

Or you could make it faster by checking that the nth character is the same as the character at the length - 1 - n position, for each n between 0 and length / 2.

This can be simplified a lot

 boolean isPalindrome = new StringBuilder(input).reverse().equals(input);

Maybe this would work for you?

String str = "madam i'm adam."; // String to compare
str = str.replaceAll("[//\\s,',,,.]",""); // Remove special characters
int len = str.length();
boolean isSame = false;

for(int i =0; i<len;i++){
    if(str.charAt(i) == str.charAt(len-1-i)){
        isSame = true;
    }
    else{
        isSame = false;
        break;
    }
}
if(isSame){
    System.out.print("Equal");
}
else{
    System.out.print("Not equal");
}
i=0;
j=str.length()-1; //length of given string
String str; // your input string
while((i<j)||(i!=j)){
    if(str.charAt(i)!=str.charAt(j)){
               System.out.println("not palindrome");
                     break;
                   }
    i++;
    j--;
}
System.out.print("palindrome");
//this can used for checking without the need of generating and storing a reverse string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top