error: illegal start of type

為{幸葍}努か 提交于 2019-12-29 07:24:11

问题


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...

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,


回答1:


You can't use for loop in class level. Put them inside a method or a block

Also java.util.Stack in Java don't have such constructor.

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



回答2:


You cannot use for loop inside a class body, you need to put them in some kind of method.

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:


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. The JVM will call that method on program startup. Please notice that I've added the code word static to your variables, so they could be directly used in the static method main.



来源:https://stackoverflow.com/questions/26502235/error-illegal-start-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!