Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java堆栈类强制转换异常_Java_Generics_Stack_Classcastexception - Fatal编程技术网

Java堆栈类强制转换异常

Java堆栈类强制转换异常,java,generics,stack,classcastexception,Java,Generics,Stack,Classcastexception,我必须编写一个程序,从键盘读取后缀表达式并将其存储在堆栈中。我一直在case“+”中得到一个类强制转换异常:我无法理解它。有人能帮我吗 String option = (String)stack.pop(); while( stack != null ) { switch( option ) { case "+": int left = (Integer)stack.pop();

我必须编写一个程序,从键盘读取后缀表达式并将其存储在堆栈中。我一直在case“+”中得到一个类强制转换异常:我无法理解它。有人能帮我吗

    String option = (String)stack.pop();
    while( stack  != null )
    {
        switch( option )
        {
        case "+":

            int left = (Integer)stack.pop();
            int right = (Integer)stack.pop();
            int result = left + right;
            String temp = (String) stack.pop();
            stack.push(result);

            break;  

你在不检查东西是什么的情况下从你的堆栈中弹出东西。这几乎肯定会给你带来麻烦。首先,您是如何构建堆栈的?你知道你一直在做这样的事情吗

stack.push("string that becomes temp");
stack.push(new Integer(5));
stack.push(new Integer(3));
stack.push("+")

看起来您正试图从堆栈中读取一系列字符串输入,并在需要使用转换时使用转换来转换数字输入

假设您的用户已经导致了这样的堆栈推送

stack.push("1234");
stack.push("1");
stack.push("+");
pop例程如下所示:

int left = Integer.parseint(stack.pop());
int right = Integer.parseint(stack.pop());
int result = left + right;
当对象的类型为所需类型时,可以使用强制转换。转换适用于您希望它成为正确类型的情况

我还将使您的堆栈成为字符串类型的通用堆栈,以避免产生疑问:

Stack<String> stack = new ....;
Stack-Stack=new。。。。;

堆栈跟踪在哪里?您需要将堆栈跟踪添加到问题中。在我们能够准确地看到错误和行引用之前,我们无法告诉您问题是什么是第一个类强制转换异常的源。
Integer.parseint
获取字符串并返回整数。如果堆栈不是类型,则必须在从
pop()
函数返回时执行
toString()
,或者执行cast-
(String)
。我建议堆栈有一个类型-
堆栈