Java从堆栈返回字符串

Java从堆栈返回字符串,java,string,stack,return,Java,String,Stack,Return,我应该使用一个helper方法反转句子中的单个单词,该方法将字符串作为参数并返回字符串。堆栈应该在helper方法中。因此,我的程序的工作原理是正确地反转单词。但是反向并没有被返回,我想它只是打印堆栈。有人能帮我返回并打印字符串变量“reverse”吗 import java.util.Scanner; import java.util.Stack; public class ReverseStack { public static void main(String[] args)

我应该使用一个helper方法反转句子中的单个单词,该方法将字符串作为参数并返回字符串。堆栈应该在helper方法中。因此,我的程序的工作原理是正确地反转单词。但是反向并没有被返回,我想它只是打印堆栈。有人能帮我返回并打印字符串变量“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;
    }   
}
import java.util.Scanner;
导入java.util.Stack;
公务舱倒排
{
公共静态void main(字符串[]args)
{
串句;
System.out.print(“输入句子:”);
扫描仪扫描=新扫描仪(System.in);
句子=scan.nextLine();
System.out.println(“反转:“+PrintStack(句子));
}
私有静态字符串打印堆栈(字符串语句)
{
字符串反向=”;
字符串next=“”;
堆栈=新堆栈();
字符串单词[]=句子。拆分(“”);

对于(int j=1;j您将反转两次,并以相同的顺序结束。堆栈给出相反的顺序,但您以相反的顺序添加单词,因此顺序不变

如果您使用了调试器,那么您应该清楚问题所在

顺便说一句,你可以使代码更短

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;
}   
私有静态字符串打印堆栈(字符串语句){
堆栈=新堆栈();
for(字符串字:句子.split(“”)
栈.推(字);
字符串行=stack.pop();
而(!stack.isEmpty())
行+=“”+stack.pop();
回流线;
}   

字符串是不可变的。您的程序正在返回并打印字符串变量“reverse”。@Simon但它不是打印堆栈而不是反向字符串吗?它的打印堆栈(句子)不是reverse@user3071909好吧,我们可以说您正在打印这两个:'PrintStack(句子)'因为您在Sysout内部调用它,而'reverse'是'PrintStack'方法的返回值。那么,我不明白您怎么看。@Simon Oohh,所以它是返回和反向打印。我只是感到困惑。堆栈的使用是否正确,就反转单词而言?