错误:非法启动类型

为什么这一小段代码在第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类,

你不能在类级别使用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); 

你不能在类体内使用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 

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

 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 

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