主类方法在类错误中不是静态的 [英] Main method is not static in class error
问题描述
class useTent
{
Scanner keyboard=new Scanner (System.in);
public void main (String[] args)
{
Tent t= new Tent();
HireContract hc = new HireContract();
ProcessHire(t, hc);
}
}
这是我的代码,我一直都是这样错误:
this is my code, and i keep getting the same error:
主要方法在类useTent中不是静态的,请将main方法定义为:
public static void main( String [] args)
" Main method is not static in class useTent, please define the main method as: public static void main(String[] args) "
当我将其设为静态时,我收到以下错误:
and when i make the it static i get the following error:
C:\ Users \Emma \Documents\opps ass1 \useTent.java:22:error:natic static method
ProcessHire( Tent,HireContract)不能从静态上下文ProcessHire(t,hc)引用;
"C:\Users\Emma\Documents\opps ass1\useTent.java:22: error: non-static method ProcessHire(Tent,HireContract) cannot be referenced from a static context ProcessHire(t, hc);"
并且还是
错误:主要方法在类useTent中不是静态的,请将main方法定义为:
public static void main(String [] args )
"Error: Main method is not static in class useTent, please define the main method as: public static void main(String[] args)"
推荐答案
Java默认查找方法
Java by default looks for a method
public static void main (String[] args) { }
或者说
public static void main (String ...args) {}
args可以是任何名称,如
public static void main(String ... arguments){}
args could be any name like public static void main (String ...arguments) {}
如果你已经有一个公共静态void main方法然后你可以有另一个main方法作为普通方法。
If you already have a public static void main method then you can have another main method which would act as normal method.
现在当你使方法静态时你会得到另一个错误,因为在静态上下文中,调用非静态方法(本地到类)而不初始化它的对象会产生错误,因为java不允许来自静态上下文/方法的非静态调用。
Now when you make the method static you get the other error because in a static context, calling a non static method(local to class) without initializing it's object would give error as java don't allow non static calls from static context/methods.
non-static method error
一个示例解决方案是使ProcessHire方法静态: -
One example solution is make ProcessHire method static:-
class UseTent
{
Scanner keyboard=new Scanner (System.in);
public void main (String[] args)
{
Tent t= new Tent();
HireContract hc = new HireContract();
ProcessHire(t, hc);
}
public static void processProcessHire(Tent tent,HireContract hireContract){
//your method definition
}
}
或者如果你不能使方法静态,那么使用下面的方法: -
or if you can't make the method static then use approach below:-
class UseTent
{
Scanner keyboard=new Scanner (System.in);
public void main (String[] args)
{
Tent t= new Tent();
HireContract hc = new HireContract();
new UseTent().ProcessHire(t, hc);
}
public void processProcessHire(Tent tent,HireContract hireContract){
//your method definition
}
}
这篇关于主类方法在类错误中不是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!