What I'm trying to do is to get the eval variable to have each of its letters put into a stack and then printed out. I'm getting an EmptyStackException error(assuming that means that there isn't anything in the stack). What I don't understand is that I thought that the eval string was put into the variable stack. Why is it empty?
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());
}
}
}
}
Im using eclipse
Sample Runs:
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)
There's a few issues I can see:
eval.substring(i,i); will return an empty string every time. You want eval.substring(i,i + 1);, or even better, eval.charAt(i);.
You'll want to put the returned substring/charAt character in it's own variable within your for loop. Currently it is overriding the eval string after the first iteration.
if (eval.equals(alphabet.substring(0, 52))) doesn't do what you seem to think it does judging by your comment. If you want to check if a string contains another string (or even just a single character), use the methods: String#contains or String#indexOf.
Here's a simple corrected snippet:
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With