[英]Java returning a string from a stack
我应该使用一个将字符串作为参数并返回字符串的辅助方法来反转句子中的单个单词。 该堆栈应该在辅助方法中。 因此,我的程序的工作方式是正确地反转了单词。 但是反向实际上并没有返回,我认为它只是打印堆栈。 谁能帮助我返回并打印字符串变量“ 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;
}
}
您正反转两次并以相同顺序结束。 您的堆栈给出了相反的顺序,但是您要按相反的顺序添加单词,因此顺序不变。
如果您使用了调试器,那么问题出在哪儿应该很明显。
顺便说一句,您可以使代码更短。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.