class LeapYear
{
public static void main(String[] args)
{
IsLeapYear(1999);
IsLeapYear(2008);
}
static void IsLeapYear(int year)//这个地方为什么去掉public就会报错呢
{ boolean flag;
flag=false;
if(year%4==0){flag=true;}
if(year%400==0){flag=true;}
if(year%100==0){flag=false;}
if(flag)
{
System.out.println(""+year+"is LeapYear.");
}
else
{
System.out.println(""+year+"is not LeapYear.");
}
}
}报错为:LeapYear.java:5: non-static method IsLeapYear(int) cannot be referenced from a s
tatic context
IsLeapYear(1999);
^
LeapYear.java:6: non-static method IsLeapYear(int) cannot be referenced from a s
tatic context
IsLeapYear(2008);
^
2 errors
{
public static void main(String[] args)
{
IsLeapYear(1999);
IsLeapYear(2008);
}
static void IsLeapYear(int year)//这个地方为什么去掉public就会报错呢
{ boolean flag;
flag=false;
if(year%4==0){flag=true;}
if(year%400==0){flag=true;}
if(year%100==0){flag=false;}
if(flag)
{
System.out.println(""+year+"is LeapYear.");
}
else
{
System.out.println(""+year+"is not LeapYear.");
}
}
}报错为:LeapYear.java:5: non-static method IsLeapYear(int) cannot be referenced from a s
tatic context
IsLeapYear(1999);
^
LeapYear.java:6: non-static method IsLeapYear(int) cannot be referenced from a s
tatic context
IsLeapYear(2008);
^
2 errors
1,去看看书,static的内容2,简单的将,static是超脱class的方法或字段,(超脱是什么不懂的话,就当我没说喽;))
你想,然不属于某个class,调用的时候,main也不知道要用哪个对象的这个方法。3,如果写测试小算法的类,我基本上这样写class LeapYear
{ public LeapYear(){
IsLeapYear(1999);
IsLeapYear(2008);
} public static void main(String[] args)
{
new LeapYear();
}
void IsLeapYear(int year) { boolean flag;
flag=false;
if(year%4==0){flag=true;}
if(year%400==0){flag=true;}
if(year%100==0){flag=false;}
if(flag)
{
System.out.println(""+year+"is LeapYear.");
}
else
{
System.out.println(""+year+"is not LeapYear.");
}
}
} 这样的话,以后要直接用的话,把main去掉就差不多ok了!good luck
你的main方法中,沒有任何類的對象,而使用類方法的途徑不當,使用類方法不需要對象,但也要指明哪個類才行,main方法不是類的方法,是程序運行的地方
1)static修饰的东西代表的都是属于类的,跟对象无关,所有对象共享
2)引用static修饰的东西,最好直接用类进行调用,用对象也可,不推荐。
貌似楼主程序没错误,请仔细在检查
可以运行,输入结果也正确1999is not LeapYear.
2008is LeapYear.