【问题标题】:error: illegal start of type错误:类型的非法开始
【发布时间】:2014-12-17 14:16:46
【问题描述】:

为什么这小段代码在第 6 行和第 10 行(for 循环)中给出非法类型错误开始...我找不到任何不匹配的大括号...

class StackDemo{
    final int size = 10;
    Stack s = new Stack(size);

    //Push charecters into the stack
    for(int i=0; i<size; i++){
        s.push((char)'A'+i);
    }
    //pop the stack untill its empty
    for(int i=0; i<size; i++){
        System.out.println("Pooped element "+i+" is "+ s.pop());
    }
}

我已经实现了 Stack 类,

【问题讨论】:

  • 离题,但您应该检查弹出和便便之间的区别。大声笑。
  • 我可以删除我自己的问题吗?我犯这个错误的愚蠢程度.....ugghhhhhhhh
  • @m.souvik 你不能。因为这里有答案。下一次之前赶紧问一个问题。请花一些时间自己解决问题。

标签: java compiler-errors stack


【解决方案1】:

您不能在班级级别使用for 循环。将它们放在methodblock

Java 中的 java.util.Stack 也没有这样的构造函数。

应该是

Stack s = new Stack()

另一个问题

s.push(char('A'+i))// you will get Unexpected Token error here

改成

s.push('A'+i);

【讨论】:

    【解决方案2】:

    你不能在类体内使用 for 循环,你需要把它们放在某种方法中。

    class StackDemo{
    final int size = 10;
    Stack s = new Stack(size);
    public void run(){
       //Push charecters into the stack
       for(int i=0; i<size; i++){
           s.push(char('A'+i));
       }
       //pop the stack untill its empty
       for(int i=0; i<size; i++){
          System.out.println("Pooped element "+i+" is "+ s.pop());
       }
       }
    }
    

    【讨论】:

      【解决方案3】:

      你不能只在一个类中编写代码,你需要一个方法:

      class StackDemo{
          static final int size = 10;
          static Stack s = new Stack(size);
      
          public static void main(String[] args) {
              //Push charecters into the stack
              for(int i=0; i<size; i++){
                  s.push(char('A'+i));
              }
              //pop the stack untill its empty
              for(int i=0; i<size; i++){
                  System.out.println("Pooped element "+i+" is "+ s.pop());
              }
          }
      }
      

      main 方法是 Java 应用程序的入口点。 JVM 将在程序启动时调用该方法。请注意,我已将代码字 static 添加到您的变量中,因此它们可以直接在静态方法 main 中使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-27
        • 2014-03-09
        • 2020-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多