我有一项作业要求学校编写一个程序,该程序的结果为真或假。这是关于一年是否是闰年。我现在遇到的问题是我使用的是公共(public)静态 boolean 值而不是公共(public) boolean 值。 这是我的代码:
public class Assignment {
static boolean isLeapYear;
public static void main(String[] args)
{
int year = 2000;
isLeapYear(year);
}
public static boolean isLeapYear(int year) {
if (((year/100)%4 == 0 && year%4 ==0) || (year % 400 == 0))
isLeapYear = true;
else
isLeapYear = false;
System.out.println(isLeapYear);
return isLeapYear;
}
}
目前的整数年是 2000 年,但规则是这样的: 闰年是可以除以 4 的年份,除非该年份是新世纪的开始(1700、1800、1900 .....)。所以即使你可以将 1900 除以 4,你也不能将它除以 400,所以它是错误的。 那么问题又来了:我需要做什么才能使用公共(public) boolean 值而不是公共(public)静态 boolean 值?
最佳答案
如果你想让你的方法成为非静态的,你需要创建你的类的一个实例来从你的主方法中调用那个方法。然后您可以使您的 isLeapYear
变量成为非静态变量:-
boolean isLeapYear;
public static void main(String[] args)
{
int year = 2000;
new Assigment().isLeapYear(year);
}
public boolean isLeapYear(int year) {
// access isLeapYear as `this.isLeapYear` or just `isLeapYear`
}
但是,准确地说,您不需要将结果存储在 boolean 变量中。如果你想返回某个表达式的 boolean 值,那么你可以只返回那个表达式。
所以,只要在你的方法中加入这段代码也可以正常工作,而且它更具可读性,并且让该方法是静态的:-
return (((year/100)%4 == 0 && year%4 ==0) || (year % 400 == 0))
从你的主要电话:-
System.out.println("Year : " + year + ", is leap year: " + isLeapYear(year));
关于java - 改变静态 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13481194/