我应该使用一个将字符串作为参数并返回一个字符串的辅助方法来反转句子中的单个单词。堆栈应该是辅助方法。所以我的程序可以正确地反转单词。但反向实际上并没有返回,我认为它只是打印堆栈。任何人都可以帮我回复并打印字符串变量'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;
}
}
答案 0 :(得分:1)
您正在倒退两次并以相同的顺序结束。你的堆栈给出了相反的顺序,但你是按相反的顺序添加单词,所以顺序没有改变。
如果您使用调试器,那么问题应该是显而易见的。
BTW你可以缩短代码。
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;
}