Question

Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this.

public class Evaluator {

public static void evaluatePost(String postFix)
   {
       LinkedStack stack2 = new LinkedStack();
       int val1;
       int val2;
       int result;
       for(int i = 0; i < postFix.length(); i++)
       {
           char m = postFix.charAt(i);
           if(Character.isDigit(m))
           {
               stack2.push(m);
           }
           else
           {
               val1 = (int) stack2.pop();
               val2 =(int) stack2.pop();

               if (m == '-')
               {
                   result =val2 - val1;
               }
               else if (m == '=')
               {
                   result = val2 + val1;
               }
               else if ( m == '%')
               {
                   result = val2 % val1;
               }
               else if (m == '/')
               {
                   result = val2 / val1;
               }
               else if (m == '*')
               {
                   result = val2 * val1;
               }
               else
               {
                   result = Math.pow(val2, val1);
               }
               stack2.push(result);
              
           }
          
       }

}

Stack class

public class LinkedStack
{
   private class Node
   {
       private Object data;
       private Node next;
       public Node(Object e, Node n)
       {
           this.data = e;
           this.next = n;
       }
      
   }//end of node class
  
   private Node top;
   private int size;
  
   public LinkedStack() //constructor
   {
       this.top = null;
       this.size = 0;
   }
  
   public int size()
   {
       return this.size;
   }
  
   public boolean isEmpty()
   {
       return (this.top == null || this.size == 0);
   }
  
   public void push(Object elem)
   {
       Node nn = new Node(elem, this.top);
       this.top = nn;
       this.size++;
   }
  
   public Object pop() throws EmptyStackException
   {
       if (isEmpty())
       {
           throw new EmptyStackException("Stack is empty");
       }
       Object temp = this.top.data;
       this.top = this.top.next;
       this.size--;
       return temp;
   }
  
  
   public Object top() throws EmptyStackException
   {
       if (isEmpty())
       {
           throw new EmptyStackException("Stack is empty");
       }
       return this.top.data;
   }
  
   class EmptyStackException extends RuntimeException
   {
       public EmptyStackException(String err)
       {
           super(err);
       }

   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

/*
As pop() method have a retrun type of 'Object', and we can't convert 'Object' type to
'int' type directly. That's why java.lang.ClassCastException is being thrown.
So one possible solution is:
convert the 'Object' to string with the help of
'toString()' method of Object class and then parse this string
into Integer using 'Integer.ParseInt()' method of Integer class
*/

import java.util.*;

public class Evaluator
{
public static void main(String[] args) {
    Evaluate e = new Evaluate();
    e.evaluatePost("231*+9-");
}
}

class Evaluate {

public static void evaluatePost(String postFix)
     {
         LinkedStack stack2 = new LinkedStack();
         int val1;
         int val2;
         int result;
         for(int i = 0; i < postFix.length(); i++)
         {
             char m = postFix.charAt(i);
             if(Character.isDigit(m))
             {
                 stack2.push(m);
             }
             else
             {
                 val1 = Integer.parseInt(stack2.pop().toString()); ///// modified code
                 val2 = Integer.parseInt(stack2.pop().toString()); ///// modified code

                 if (m == '-')
                 {
                     result =val2 - val1;
                 }
                 else if (m == '=')
                 {
                     result = val2 + val1;
                 }
                 else if ( m == '%')
                 {
                     result = val2 % val1;
                 }
                 else if (m == '/')
                 {
                     result = val2 / val1;
                 }
                 else if (m == '*')
                 {
                     result = val2 * val1;
                 }
                 else
                 {
                     result = (int)Math.pow(val2, val1);
                 }
                 stack2.push(result);
              
             }
          
         }

         System.out.println(stack2.pop());
}
}

//Stack class

class LinkedStack
{
   private class Node
   {
       private Object data;
       private Node next;
       public Node(Object e, Node n)
       {
           this.data = e;
           this.next = n;
       }
    
   }//end of node class

   private Node top;
   private int size;

   public LinkedStack() //constructor
   {
       this.top = null;
       this.size = 0;
   }

   public int size()
   {
       return this.size;
   }

   public boolean isEmpty()
   {
       return (this.top == null || this.size == 0);
   }

   public void push(Object elem)
   {
       Node nn = new Node(elem, this.top);
       this.top = nn;
       this.size++;
   }

   public Object pop() throws EmptyStackException
   {
       if (isEmpty())
       {
           throw new EmptyStackException("Stack is empty");
       }
       Object temp = this.top.data;
       this.top = this.top.next;
       this.size--;
       return temp;
   }


   public Object top() throws EmptyStackException
   {
       if (isEmpty())
       {
           throw new EmptyStackException("Stack is empty");
       }
       return this.top.data;
   }

   class EmptyStackException extends RuntimeException
   {
       public EmptyStackException(String err)
       {
           super(err);
       }

   }
}

Add a comment
Know the answer?
Add Answer to:
Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Help with c++ program. The following code takes an infix expression and converts it to postfix....

    Help with c++ program. The following code takes an infix expression and converts it to postfix. When I compile the code it returns "Segmentation fault". However I don't know what causes this. #include #include #include using namespace std; template class Stack { public: Stack();//creates the stack bool isempty(); // returns true if the stack is empty T gettop();//returns the front of the list void push(T entry);//add entry to the top of the stack void pop();//remove the top of the stack...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT