此代碼是main
函數內部:反轉字符 - 棧的實現
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
這是empty()
功能:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
它不能正常工作,通過鍵入example sentence
我得到這個輸出:lpmaxe
。第一個字母丟失,循環停止,而不是計算經過空間到句子的下一部分。
我試圖做到這一點:
This is a sentence
--->sihT si a ecnetnes
顛倒句子中的單詞和句子中的字符之間存在細微的差異。你想要做什麼? – 2012-07-18 15:34:10
我想在句子中的每個單詞中反轉字符,同時保持相同的單詞順序。你可以說這是家庭作業 - 我只是在網上尋找問題,以提高我對堆棧和隊列的理解。 – amiregelz 2012-07-18 15:37:05
你有沒有試過檢查'sentence'的值是什麼,和/或['Scanner.next()'](http://docs.oracle.com/javase/6/docs/api/java /util/Scanner.html#next())說它會做? – 2012-07-18 15:38:44