简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM