问题
I keep on getting the error identifier expected. I am still learning how to call classes and I believe I am doing it wrong.
回答1:
You can't just put code inside a class - you need to put it in a method:
public class OptionFrame {
public void someMethod() {
System.out.println ("It works");
}
}
... or a constructor:
public class OptionFrame {
public OptionFrame() {
System.out.println ("It works");
}
}
... or even a static
block:
public class OptionFrame {
static {
System.out.println ("It works");
}
}
回答2:
The main issue seems to be that the call to System.out.println
is in the body of the OptionFrame
class, not in a method. Making method calls in the body of a class is incorrect (in this context).
I think this is what you mean to do, invoking the constructor on OptionFrame
:
public class OptionFrame {
public OptionFrame() {
System.out.println("It Works");
}
}
Additionally, a Java file can only contain a single class, and you have a typo in your main
method definition - change Sting
to String
. These will likely be the next compiler errors you encounter when you fix the issue above.
回答3:
public class OptionFrame {
System.out.println("It Works!")
}
You cannot do something like above. You cannot just put you code lying around. You need to out it is some block, method or a constructor
.
Also you cannot have two public
top level classes in the same file. Name of the file should be same as that of the top level public class. Remove modifier of OptionFrame
class (so it will be default) as top level classes can only be public
or default
.
回答4:
The issue is that you don't have a constructor for OptionFrame
-- remember that the format of a constructor is an identifier, then the class name, then any arguments in parentheses (and no return type specified. So an example might be:
public OptionFrame() {
...
}
Just remember that statements in classes are always grouped into three categories -- instance variables, constructors, and methods -- and watch out for any stray statements that don't fit into one of those, for example a print statement not embodied within a method or constructor.
来源:https://stackoverflow.com/questions/25585393/identifier-expected-when-trying-to-call-a-class