简体   繁体   English

错误:类型非法开始

[英]error: illegal start of type

why this little piece of code is giving illegal start of type error in line 6 and 10(for loops).... i can't find any unmatched braces... 为什么这小段代码在第6行和第10行中给出非法的类型错误开始(用于循环)...。我找不到任何不匹配的花括号...

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());
    }
}

I have the class Stack implemented, 我已经实现了Stack类

You can't use for loop in class level. 您不能在类级别使用for循环。 Put them inside a method or a block 将它们放在methodblock

Also java.util.Stack in Java don't have such constructor. Java java.util.Stack也没有这样的构造函数。

It should be 它应该是

Stack s = new Stack()

Another issue 另一个问题

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

Just change it to 只需将其更改为

s.push('A'+i);

You cannot use for loop inside a class body, you need to put them in some kind of method. 您不能在类体内使用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());
   }
   }
}

You can't just write code in a class, you need a method for that: 您不仅可以在类中编写代码,还需要一种方法:

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());
        }
    }
}

The method main is the entry point for a Java application. main方法是Java应用程序的入口点。 The JVM will call that method on program startup. JVM将在程序启动时调用该方法。 Please notice that I've added the code word static to your variables, so they could be directly used in the static method main . 请注意,我已经在您的变量中添加了static代码,因此可以将它们直接用于static方法main

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM