0
我应该使用以字符串作为参数并返回字符串的帮助器方法来颠倒句子中的单个单词。该堆栈应该是辅助方法。所以我的程序工作,它正确地反转了单词。但反向没有实际返回,我认为它只是打印堆栈。任何人都可以帮助我返回并打印字符串变量'reverse'。Java从栈中返回字符串
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;
}
}
字符串是不可变的。 – Maroun
您的程序正在返回并打印字符串变量'reverse'。 –
@Simon但它不打印出堆栈而不是反向字符串?它打印PrintStack(句子)不是反转 – user3071909