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