【问题标题】:Java '.class' expected errorJava '.class' 预期错误
【发布时间】:2013-12-12 01:17:06
【问题描述】:

我下面的代码会出现编译错误:'.class' expected:

Stack<Character> stack=new Stack<Character>();
char pop=stack.pop();

但是如果我改成这个,编译成功:

char pop;
Stack<Character> stack=new Stack<Character>();
pop=stack.pop();

什么原因?

完整代码在这里:

 public class Solution {
    public boolean isValid(String s) {

        //char pop;
        if(s==null||s.length()==0)return true;
        Stack<Character> stack=new Stack<Character>();
        stack.push(s.charAt(0));
        for(int i=1;i<s.length();i++){
            char c=s.charAt(i);
            if(c=='('||c=='['||c=='{')
                stack.push(c);
            else{
                if(!stack.isEmpty())
                    char pop=stack.pop();
                else
                    return false;
                if(c==')'&&pop!='(') return false;
                else if(c==']'&&pop!='[') return false;
                else if(c=='}'&&pop!='{') return false;
            }
        }
        return stack.isEmpty();
    }
}

【问题讨论】:

  • 那是你的完整代码吗?在它之前/之后是否有任何可能触发 .class 预期的内容?
  • 哪一行触发了错误?
  • 这本身不会导致您描述的错误。
  • 我无法重现您的错误。你能发布完整但简短的代码,让我们重现它吗?
  • 它的工作..没有编译错误。

标签: java variables loops scope global-variables


【解决方案1】:

您在 if 条件中使用 pop 作为局部变量。它应该是全局的,因为稍后您将使用 pop 值。
虽然在 else 条件下不会使用 pop。但它仍然会显示编译错误。
在您的代码 sn-p 中:

else{
            if(!stack.isEmpty())
                char pop=stack.pop(); // Here you initialized the value inside a condition.
            else
                return false;
            if(c==')'&&pop!='(') return false;
            else if(c==']'&&pop!='[') return false;// Using the value.
            else if(c=='}'&&pop!='{') return false;// Using the value.
        }

【讨论】:

    【解决方案2】:

    以下代码中可能存在问题:

    if(!stack.isEmpty())         // here you will need to provide curly braces to define pop's scope
         char pop=stack.pop();
    

    另外,如果您在外面声明 pop,我在您的注释代码 //char pop 中看到它,您将不得不删除上面的 pop 的 char 声明,如果您尝试在外面使用它会更有意义你的 if 条件。

    【讨论】:

      【解决方案3】:

      如果你的代码可以编译

      if (!stack.isEmpty())
          char pop = stack.pop();
      else
      

      is 与(注意 {...} 表示变量范围的括号)相同

      if (!stack.isEmpty()){
          char pop = stack.pop();
      } else
      

      所以这意味着您只是得到stack.pop() 的结果并将其存储在变量char pop 中,在此块之外的任何地方都无法访问。
      由于这条指令是在if 条件成功的情况下唯一执行的指令,这意味着pop() 的存储结果是多余的,并且是设计问题的标志。

      要解决此问题,请在 if 语句之前的某处声明 char pop,以便在 if 块之后访问它。

      char pop; //make sure that this variable will be initialized before you use it
      if (!stack.isEmpty())
          pop = stack.pop();
      else
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多