I am very new to coding, and I am trying to solve the following question:
Use a stack to reverse the words of a sentence. Keep reading words until you have a word that ends in a period, adding them onto a stack. When you have a word with a period, pop the words off and print them. Stop when there are no more words in the input. For example, you should turn the input:
Mary had a little lamb. Its fleece was white as snow.
into:
Lamb little a had mary. Snow as white was fleece its.
Pay attention to capitalization and the placement of the period.
I am struggling to find how to reverse the words - I have found a lot of examples of reversing characters, but I can't get anything to work to reverse full words. Here is what I have so far. I don't really understand the String[] words = sentence.split(" "); line, but I found that in a lot of solutions... Is that creating an array of words that I can then push onto the stack?
import java.util.Scanner;
import java.util.Stack;
public class Task03 {
public static void main(String[] args) {
String sentence;
System.out.println("Enter a sentence: ");
Scanner input = new Scanner(System.in);
sentence = input.next();
printStack(sentence);
}
private static void printStack(String sentence) {
Stack<String> stack = new Stack<>();
String[] sentenceArray = sentence.split(" ");
String reversed = "";
for (String words: sentenceArray) {
stack.push(words);
}
while (!stack.isEmpty()){
reversed += stack.pop();
}
System.out.println("Reverse is: " + reversed);
}
}
The output for this just returns the first word from the sentence, so I'm doing something wrong in the printStack method. I hope I have added enough to show you that I am really trying.