此代码是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