我想要做的是让 eval 变量将每个字母放入堆栈然后打印出来。我收到 EmptyStackException 错误(假设这意味着堆栈中没有任何内容)。我不明白的是,我认为将 eval 字符串放入变量堆栈中。为什么是空的?
public static void main(String[] args)
{
Stack<String> variable = new Stack<String>();
String eval = StdIn.readString();
String alphabet = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < eval.length(); i++)
{
eval = eval.substring(i,i);
if (eval.equals(alphabet.substring(0, 52)))// checks if eval is equal to any letter of alphabet
{
variable.push(eval);
System.out.println(variable.pop());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用日食
示例运行:
input: hello
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at java.util.Stack.pop(Unknown Source)
at eval.main(eval.java:31)
Run Code Online (Sandbox Code Playgroud)
我可以看到几个问题:
eval.substring(i,i);每次都会返回一个空字符串。你想要eval.substring(i,i + 1);,甚至更好,eval.charAt(i);。
您需要将返回的 substring/charAt 字符放在for循环中它自己的变量中。目前它eval在第一次迭代后覆盖字符串。
if (eval.equals(alphabet.substring(0, 52)))从您的评论来看,它并没有做您认为的事情。如果您想检查一个字符串是否包含另一个字符串(甚至只是一个字符),请使用以下方法:String#contains或String#indexOf。
这是一个简单的更正片段:
String alphabet = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String eval = "blah";
Stack<Character> chars = new Stack<Character>();
for(char c : eval.toCharArray()) {
if(alphabet.indexOf(c) != -1) {
chars.push(c);
System.out.println(chars.pop());
}
}
Run Code Online (Sandbox Code Playgroud)
您收到此错误的唯一方法是:
for (int i = 0; i < eval.length(); i++)
{
eval = eval.substring(i,i);
if (eval.equals(alphabet.substring(0, 52)))
{
variable.push(eval);
}
System.out.println(variable.pop());
}
Run Code Online (Sandbox Code Playgroud)
如果你有System.out.println(variable.pop());if 条件的 外部。
public Object pop()
Run Code Online (Sandbox Code Playgroud)
移除此堆栈顶部的对象并将该对象作为此函数的值返回。
返回: 此堆栈顶部的对象(Vector 对象的最后一项)。抛出:
EmptyStackException - 如果此堆栈为空。
在您发布的代码中,这是不可能的,因为您有相同数量的pushand pop,并且push操作先于pop。
你放的代码:

你得到的错误:
