Java 错误:类型的非法开始
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26502235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: illegal start of type
提问by SouvikMaji
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 行(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());
}
}
I have the class Stack implemented,
我实现了 Stack 类,
采纳答案by Ruchira Gayan Ranaweera
You can't use for
loop in class level. Put them inside a method
or a block
您不能for
在类级别使用循环。把它们放在 amethod
或 ablock
Also java.util.Stack
in Java
don't have such constructor.
同样java.util.Stack
在Java
没有这样的构造函数。
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);
回答by Beri
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());
}
}
}
回答by Tom
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
.
该方法main
是 Java 应用程序的入口点。JVM 将在程序启动时调用该方法。请注意,我已将代码字添加static
到您的变量中,因此它们可以直接在静态方法中使用main
。