-1
import java.util.Scanner;

public class palindrome {

    public static void main(String[] args) {
        
        
        Scanner sc = new Scanner(System.in);
        String word = sc.next();
        String org_word = word;
        word = word.replace(" ","");
        String reverse = "";
        for (int i = word.length()-1;  i >=0; i--) {
            
            reverse += word.charAt(i);
            
        }
        
        boolean palindrome = true;
        for (int i= 0; i < word.length(); i++){
            
            if(word.charAt(i) != reverse.charAt(i)){
                
                palindrome = false;
                
            }
        }
        if (palindrome) {
            
            System.out.println("Your word is a palindrome!");
        }
    
        else System.out.println("Your word is not a palindrome!");
    }

}

If I put a Palindrome in my Program like "racecar" it does it correctly, but if I type "race car" with a space, it doesn't work. Neither does it when I start a word with a capital letter.

khelwood
  • 55,782
  • 14
  • 81
  • 108
NonoTheGR
  • 1
  • 1
  • 3
    The simple method would be to just make the string all lowercase and remove everything that is not a letter. – dan1st Mar 07 '21 at 21:37

1 Answers1

1

You are using scanner.next() to read in your arguments. In the case of a race car, this means it will read in the first word: race. Which is indeed not a palindrome. To solve this, you need to use scanner.nextLine() to read everything until the next line.

For ignoring case sensitivity, you could change all input to lower case. The string method has a very usefull out of the box method: toLowerCase()

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String word = sc.nextLine();

    word = word.replace(" ", "");
    word = word.toLowerCase();
    String reverse = "";
    for (int i = word.length() - 1; i >= 0; i--) {

        reverse += word.charAt(i);

    }

    boolean palindrome = true;
    for (int i = 0; i < word.length(); i++) {

        if (word.charAt(i) != reverse.charAt(i)) {

            palindrome = false;

        }
    }
    if (palindrome) {
        System.out.println("Your word is a palindrome!");
    } else {
        System.out.println("Your word is not a palindrome!");
    }
}
Yoni
  • 1,370
  • 7
  • 17