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);
}
}
You can split your task:
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);
}