-2

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.

bacon
  • 1
  • 1
  • the point of this assignment is for you to learn how to think about processing data using algorithms and logic. *I do not know where to start* is kind of the point, you are supposed to **try** something on your own to form the logic yourself. –  Nov 18 '15 at 18:21

1 Answers1

0

I have hard coded the string value. you can take input from user too

class StringRev{
    public static void main(String args[]){
    String str = "He is the one";
    String temp = "";
    String finalString = "";
        for(int i =str.length()-1;i>=0;i--){
            temp +=i!=0?str.charAt(i):str.charAt(i)+" ";
            if(str.charAt(i) == ' '||i==0){
                for(int j=temp.length()-1;j>=0;j--){
                    finalString += temp.charAt(j);
                }
                temp = "";
            }
        }
            System.out.println(finalString);
    }
}
Mukesh Kumar
  • 317
  • 1
  • 5
  • 16