【发布时间】:2015-04-22 02:38:24
【问题描述】:
所以我正在尝试创建一个对象,该对象基本上反转某人输入的字符串。我能够让它反转单词顺序,但我需要让它使用堆栈来反转单词本身,所以这是我将字母输入堆栈的代码。
public class Reverser
{
private Stack<String> stack;
public Reverser()
{
stack = new Stack<String>();
}
public String evaluate(String expr)
{
Scanner in = new Scanner(expr);
char letter;
String sentence="";
String rSent="";
String word="";
while(in.hasNext())
{
sentence = in.next();
for (int i = 1; i <= sentence.length(); i++)
{
while (i <= sentence.length())
{
letter = sentence.charAt(i);
word += letter;
}
stack.push(word);
}
}
while (!stack.isEmpty())
{
word = stack.pop();
rSent += word;
}
return rSent;
}
}
编译正常没有问题,但是当我运行我的驱动程序时
public class StringReversing
{
public static void main(String[] args)
{
String sentence, result, again;
Scanner in = new Scanner(System.in);
do
{
Reverser evaluator = new Reverser();
System.out.println("Please enter a sentence");
sentence = in.nextLine();
result = evaluator.evaluate(sentence);
System.out.println();
System.out.println("Your sentence reversed is:");
System.out.println(result);
System.out.println("Would you like to reverse another sentence [Y/N]?");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("y"));
}
}
现在我输入一个句子,我什么也得不到。我错过了什么吗?
【问题讨论】:
-
您能否详细说明“我能够让它反转单词顺序,但我需要让它使用堆栈来反转单词本身”是什么意思?您是否需要在某些作业问题中使用堆栈?为什么不使用 StringBuilder.reverse?
-
是的,这是一项要求我使用堆栈来反转单词字母的作业。最初,我能够让它颠倒单词顺序——祝你有美好的一天。变成了day.niceaHave
标签: java