java.lang ClassCastException错误

时间:2016-03-10 00:23:54

标签: java exception

我的任务是在java中创建一个postFixEvaluator,每当我尝试使用evaluateTwoOperations方法弹出一个操作数时,我的程序结束并产生以下错误。是什么造成的?据我所知,我所拥有的一切都是复杂而不是整数。

“无法运行PostfixEvaluator!java.lang.ClassCastException:java.lang.Integer无法强制转换为Complex”

开始我的postFixEvaluator类

 @author Cody
 */
import java.util.*;
import java.io.*;
import java.util.StringTokenizer;

public class PostfixEvaluator
{

   private static final int STACK_SIZE = 100;
   private Stack operand;
   private String expression;
   private ArrayList<Complex> answers;
   public static Complex result;

   public void run() throws IOException
   {
      ArrayList<Complex> a = new ArrayList<>();
      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      //BufferedReader stdin = new BufferedReader(new FileReader("Prog3_1.in"));
      operand = new Stack(STACK_SIZE);
      boolean eof = false;
      while (!eof) //while not done
      {
         expression = stdin.readLine(); //read a line of expression
         //operand.clear(); //clear the stack
         if (expression == null) //if no input, end program
         {
            eof = true;
         }
         else
         {
            result = evaluate(expression); //evaluate expression
         }
         if (result != null) //if the answer is valid
         {
            System.out.println("\nvalue: " + result.toString());
            answers.add(result);//add answer to arrayList
         }
         else
         {
            System.out.println("\nInvalid Expression");
         }
      }
      //read the ArrayList and print the results
      /*
      if (real)
      /
      for (int i = 0; i < answers.size(); i++)
      {
         System.out.println(answers.get(i));
      }
      */
      System.out.println("Normal termination of"
            + "program 3");

   }

   public Complex evaluate(String expression)
   {
      boolean valid = true;
      StringTokenizer st = new StringTokenizer(expression); //tokenize the expression
      String token; //get individual results of readLine
      while (valid && st.hasMoreTokens()) //while valid and their are tokens remaining
      {
         token = st.nextToken(); //get next token
         System.out.println("token is: " + token);
         if (isOperator(token)) //if token is operator
         {
            if (isConjugate(token))
            {// if token is conjugate
               Complex result1 = evaluateConjugate(token);
               operand.push(result1);
            }
            else //evaluate the operator and push the result
            {
               Complex result1 = evaluateTwoOperations(token);
               operand.push(result1);
            }
         }
         else 
         {
            int value = Integer.parseInt(token);
            operand.push(value);
         }
      }
      Complex answer = (Complex) operand.pop();
      return answer;
   }

   private Complex evaluateTwoOperations(String op)
   {
      Complex resultant = null;
      if ( operand.isEmpty() )
         System.out.println("Invalid Expression!");
      else
      {
      Complex op2 = (Complex) operand.pop();
      Complex op1 = (Complex) operand.pop();


      switch (op.charAt(0)) //if op == '+'...
      {
         case '+':
            resultant = op1.plus(op2);
            break;
         case '-':
            resultant = op1.minus(op2);
         case '*':
            resultant = op1.times(op2);
      }
      return resultant;
      }
      return null;
   }

   private boolean isOperator(String token)
   {
      return token.equals("+") || token.equals("-")
            || token.equals("*") || token.equals("~");
   }

   private boolean isConjugate(String token)
   {
      return token.equals("~");
   }

   private Complex evaluateConjugate(String op)
   {
      Complex resultant = null;
      if (operand.isEmpty())
         System.out.println("Invalid Expression!");
      else
      {
      Complex op1 = (Complex) operand.pop();

      switch (op.charAt(0)) //if op == '~'
      {
         case '~':
            resultant = op1.conjugate();
      }
      return resultant;
      }
      return null;
   }
/*
   private void outputExpression(String expression)
   {
      for (int i = 1; i < answers.size(); i++)
      {
         System.out.println("Expression " + i + ": " + expression);
      }

   }
   */

}

开始我的复杂课程

 @author Cody
 */
public class Complex
{

   private int realNumber;
   private int imagNumber;
   private final int checker = 0;

   /**
   default constructor creates the default complex number a+bi where a=b=0.
    */
   public Complex()
   {
      realNumber = checker;
      imagNumber = checker;
   }

   /**
   parameterized constructor creates the complex number a+bi, where b=0.
    */
   public Complex(int real)
   {
      realNumber = real;
      imagNumber = checker;
   }

   /**
   parameterized constructor creates the complex number a+bi where a and b are
   integers.
    */
   public Complex(int real, int imag)
   {
      realNumber = real;
      imagNumber = imag;
   }

   /**
   method returns a new Complex number that represents the sum
   of two Complex numbers.
   @param cp
   @return new summed complex number
    */
   public Complex plus(Complex cp)
   {
      return new Complex(realNumber + cp.realNumber, imagNumber + cp.imagNumber);
   }

   /**
   method returns a new Complex that represents the difference
   between two Complex numbers
   @param cp
   @return difference of two Complex numbers
    */
   public Complex minus(Complex cp)
   {
      return new Complex(realNumber - cp.realNumber, imagNumber - cp.imagNumber);
   }

   /**
   method returns a new Complex that represents the product of
   two Complex numbers
   @param cp
   @return product of two complex numbers
    */
   public Complex times(Complex cp)
   {
      return new Complex(realNumber * cp.realNumber - imagNumber * cp.imagNumber,
            realNumber * cp.realNumber + imagNumber * cp.realNumber);
   }

   /**
   method should return a new Complex that is the conjugate of a
   Complex number
   @param none
   @return conjugate of complex number
    */
   public Complex conjugate()
   {
      return new Complex(realNumber, -imagNumber);
   }

   /**
   method returns true if two Complex numbers have the same
   real and imaginary; return false otherwise.
   @param obj
   @return true if two complex numbers are equal, false otherwise
    */
   public boolean equals(Object obj)
   {
      if (obj instanceof Complex)
      {
         Complex n = (Complex) obj;
         return n.realNumber == realNumber && n.imagNumber == imagNumber;
      }
      return false;
   }

   /**
   method returns a complex number as a String.
   uses multiple if statements to check validity
   @param none
   @return complex number as a string
    */
   public String toString()
   {
      if (imagNumber == checker)
      {
         return String.valueOf(realNumber);
      }
      if (realNumber == checker && imagNumber == checker)
      {
         return String.valueOf(checker);
      }
      if (realNumber == checker)
      {
         return imagNumber + "i";
      }
      if (realNumber != checker && imagNumber < checker)
      {
         return realNumber + " - " + -imagNumber + "i";
      }
      if (realNumber != checker && imagNumber > checker)
      {
         return realNumber + " + " + imagNumber + "i";
      }
      return "invalid";
   }
}

开始我的Stack类

/**
 performs all practical Stack operations
 @author Cody
 */
public class Stack
{
   private Object[] elements;
   private int top;

   /**
    parameterized constructor creates array of Elements with size of size
    initializes top to 0
   @param size
    */
   public Stack(int size)
   {
      elements = new Object[size];
      top = 0;
   }

   /**
    checks to see if the array is empty
    @param none
    @return true if array is empty, false otherwise.
    */
   public boolean isEmpty()
   {
      return top == 0;
   }

   /**
    checks to see if the array is full
    @param none
    @return true if array is full, false otherwise.
    */
   public boolean isFull()
   {
      return top == elements.length;
   }

   /**
    returns the item most recently added to the stack. if the array is empty,
    returns null
    @param none
    @return last item added to stack, null if empty array
    */
   public Object peek()
   {
      if (top == 0)
         return null;
      return elements[top - 1];
   }

   /**
    returns and deletes element most recently added to the stack
    @param none
    @return element most recently added to stack
    */
   public Object pop()
   {
      return elements[--top];
   }

   /**
    adds item to stack and increments top
    @param obj
    */
   public void push(Object obj)
   {
      elements[top++] = obj;
   }

   /**
    returns number of items in stack
    @param none
    @return number of items in stack
    */
   public int size()
   {
      return elements.length;
   }

   /**
    clears the stack by popping everything in it
    @param none

    */
   public void clear()
   {
      for (int i = 0; i < size(); i++)
         elements[i] = pop();
   }

}

1 个答案:

答案 0 :(得分:0)

在你的评估方法中,你有这段代码:

int value = Integer.parseInt(token); operand.push(value);

但是当你弹出这样的值时,你会在evaluateTwoOperations方法中将它转换为(Complex)。因此,您将获得ClassCastException。

您已经有一个构造函数可以帮助您将Integer转换为Complex类 你可以使用它。

public Complex(int real)
   {
      realNumber = real;
      imagNumber = checker;
   }