所以我试图创建一个基本上反转某个输入字符串的对象。我能够让它反转单词顺序,但我需要让它使用堆栈来反转单词本身,这是我将代码输入堆栈的代码。
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"));
}
}
现在我输入一个句子而我什么都没得到。我错过了什么吗?
答案 0 :(得分:0)
你得到一个无限循环:
for (int i = 1; i <= sentence.length(); i++)
{
while (i <= sentence.length())
{
letter = sentence.charAt(i);
word += letter;
}
stack.push(word);
}
内部while
循环是无限循环,因为我将永远相同且低于sentence.length()
。
java中的数组基于零。你for
循环从零开始。
答案 1 :(得分:0)
这不会解决您的要求吗?
String input = "I like this CAFEBABE.";
System.out.println("reversed: " + new StringBuilder(input).reverse());