Java 错误:类型的开头非法
为什么这段代码在循环的第6行和第10行中给出非法的类型开头错误。。。。我找不到任何不匹配的大括号Java 错误:类型的开头非法,java,compiler-errors,stack,Java,Compiler Errors,Stack,为什么这段代码在循环的第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 u
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());
}
}
我已经实现了类堆栈,您不能在类级别使用for循环。将它们放在方法或块中
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<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());
}
}
}
您不能只在类中编写代码,您需要一个方法:
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添加到变量中,因此可以直接在static方法main中使用它们。Offtopic,但您应该检查popped和popped之间的差异。哈哈。我可以删除我自己的问题吗?我犯那个错误的愚蠢程度。。。。。ugghhhhhhhh@m.souvik你不能。因为这里有答案。下次之前,赶紧问个问题。请自己花点时间来解决这个问题。