Search code examples
javastringpalindrome

Print couple of Palindromes out of a user input


I would like to print a few words out of a user input, for example for that sentence: " we love mom and dad" the program will print "mom dad" I have no idea how to print those words. just the chars m and d. Much Appreciate ! here is my code:

        Scanner s = new Scanner(System.in);
    System.out.println("Please enter a Sentence");
    String input = s.nextLine();
    String output = "";
    for (int i = 0, j = 0; i < input.length(); i++) {
        if (input.charAt(i) == ' ') {
            j = i + 1;
        }
        if (j < i && input.charAt(j) == input.charAt(i)) {
             output=output+(input.charAt(i);
        }
    }
    System.out.println(output);
}

}


Solution

  • You can split your task:

    1. Create method what checks if String is palindrome. Examples
    2. Split input line by space and in loop check every String if is it palindrome. Print it or store, you have to choose:

    Save result in String, using concatenation.

    String input = s.nextLine();
    String result = "";
    for(String word : input .split(" ")) {
        if(isPalindrome(word))
            result += word + " ";
    }
    

    Save palindrome words in ArrayList.

    String input = s.nextLine();
    List<String> words = new ArrayList<>();
    for(String word : input .split(" ")) {
        if(isPalindrome(word))
            list.add(word);
    }