-1

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);
}

}

Tal Ouzan
  • 75
  • 1
  • 5
  • 4
    Didn't you just ask that question: https://stackoverflow.com/questions/60059612/how-to-print-a-single-word-out-of-a-user-input – Andronicus Feb 04 '20 at 18:23
  • No because it wasnt palindrome. just a single word – Tal Ouzan Feb 04 '20 at 18:24
  • 4
    @TalOuzan This problem consists of a few steps: 1) Break a sentence into individual words, 2) Test each word to see if it's a palindrome, and 3) Print out the entire word if it's a palindrome. Right now it looks like you're not really doing any of those things. The first step would be to break the sentence into words. So start with that, and see if you can accomplish it. Then move on from there. – Jordan Feb 04 '20 at 18:45

2 Answers2

1

Here is how I would go about solving this.

  1. Split the string on spaces (assuming you don't need to worry about punctuation)
  2. Loop through the array you get from splitting and reverse all of the strings using a StringBuilder. (save these reverse strings in a new array)
  3. lastly, loop through both arrays using a double for loop comparing the strings in the reversed array and the original. If a word is the same, it's a palindrome and you can print it or do whatever with it.
rhowell
  • 1,165
  • 8
  • 21
1

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);
}