user3071909
user3071909

Reputation: 15

Java returning a string from a stack

I am supposed to reverse the individual words in a sentence using a helper method that takes a string as a parameter and returns a string. The stack is supposed to be in the helper method. So my program works in that it reverses the words correctly. But reverse isnt actually getting returned, i think its just printing the stack. Can anyone help me return and print the string variable 'reverse'.

import java.util.Scanner;
import java.util.Stack;

public class ReverseStack 
{
    public static void main(String[] args)
    {
        String sentence;

        System.out.print("Enter a sentence: ");
        Scanner scan = new Scanner(System.in);

        sentence = scan.nextLine();

        System.out.println("Reversed:" + PrintStack(sentence));
    }

    private static String PrintStack(String sentence)
    {
        String reverse = "";
        String next = "";

        Stack<String> stack= new Stack<String>();

        String words[] = sentence.split(" ");

        for(int j = 1; j<words.length +1; j++)
        {
            String newWord = words[words.length - j]; // Single word

             for(int i = 0; i < newWord.length(); i++)
            {
                    next = newWord.substring(i,i+1);
                    stack.push(next);
            }
             stack.push(" ");
        }
        while(!stack.isEmpty())
        {
            reverse += stack.pop();
        }
        return reverse;
    }   
}

Upvotes: 0

Views: 155

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

You are reversing twice and ending up with the same order. Your Stack gives reverse order, but you are adding the words in reverse order, so the order is unchanged.

If you used a debugger it should be obvious to you what the issues is.

BTW You can make the code much shorter.

private static String printStack(String sentence) {
    Stack<String> stack= new Stack<String>();
    for(String word: sentence.split(" ")
        stack.push(word);
    String line = stack.pop();
    while(!stack.isEmpty())
        line += " " + stack.pop();
    return line;
}   

Upvotes: 1

Related Questions