I am writing an evaluation code for polish notation. When I overcome ClassCastException I get EmptyStack and when I solve Emptystack I get ClassCast I'm in a loop.
Here is how I wanted to evaluate the Polish notation:
First I get a string from the user then put it into a stack. For evaluating I use a second stack. Why?
Because:
An example string: "* + * + 1 2 + 3 4 5 6" First operation here is to add up 3 and 4 but what I'm gonna do with 5 and 6? I put them in another stack. Let's say stack2. I start popping until I found an operator, in this condition I pushed 6 5 4 3 into stack2 and found a plus operator. Then I pop 2 numbers which I pushed to stack2 (the top 2 numbers are 3 and 4), add them up, and push them to stack again.
I should evaluate but seems like I am missing a point or this wasn't a good idea at first.
Here is my code:
public class Main {
public static void stack(String srt){ // this function puts the string in srt stack
String arr[] = srt.split(" "); // I am recognizing if there is a 2 or more digit number
int size= arr.length; // with receiving prefix with " " btw every number and operator
Stack stack= new Stack();
for (String s : arr) {
// System.out.println(s);
stack.push(s);
}
// for (int i = 0; i < size; i++) {
// System.out.println(stack.pop()); // I checked to see if any
// problems first now I dont start this
// }
evaluate(stack); // then calls the evaluate function
}
public static void evaluate(Stack stack){
Stack stack2= new Stack();
stack2.push(stack.pop());// cuz of there cant be an operator there I pop first 2 number
stack2.push(stack.pop());
for (int i = 0; i < (stack.capacity()*2); i++) { // I had a hard time calculating how many times
// I should cycle through this for and leave it 2 times as stack capacity
if(stack.peek().toString().equals("*") || stack.peek().toString().equals("-") || stack.peek().toString().equals("/") || stack.peek().toString().equals("+")){
System.out.println("Checkpoint1");
// System.out.println(stack2.peek());
int s2= Integer.parseInt((String) stack2.pop());
int s1= Integer.parseInt((String) stack2.pop());
double s3;
String c = (String) stack.pop();
switch (c) {
case "+":
s3=s1+s2;
stack2.push(s3);
case "-":
s3=s1-s2;
stack2.push(s3);
case "*":
s3=s1*s2;
stack2.push(s3);
case "/":
s3=s1/s2;
stack2.push(s3);
}
}else{
System.out.println("Checkpoint 2");
stack2.push(Integer.parseInt((String) stack.pop()));
// System.out.println(stack.peek());
}
}
// System.out.println(stack.peek());
// System.out.println(stack2.peek());
}
public static void main(String[] args) {
String examplestr ="* + * + 1 2 + 3 4 5 6";
stack(examplestr);
}
}
Thank you for your help!!!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…