public class LeapYear_2 {
public static void main(String[] args) {
int year = 1900;
while (year <= 2100 && (year % 4 == 0)){
System.out.println(year + " Is a Leap Year");
year++;
System.out.println(year + " Is not a leap year");
year++;
}
}
}
我只想知道我的代码有什么问题吗?我想创建一个程序,该程序将在1900年到2100年之间显示and年,而这不是。
我只是不知道如何在许多条件下使用...似乎为了使该程序能够按我的意愿工作,我必须在while循环中具有许多条件。
公共课程TestLeapYear {
public static void main(String[] args) {
int year = 1900;
while (year <= 2100 ){
if (year % 4 == 0){
System.out.println(year + " Is a Leap Year");
year++;
}
else {
System.out.println(year + " Is not a leap year");
year++;
}
}
}
}
此代码遍历从1900年到2100年的所有年份,并针对每个年份检查是否为a年(year%4 == 0)。然后将进行相应打印。
编辑:您也可以使用三元运算符(条件?doIfTrue:doIfFalse)在一行中执行此操作(但它的可读性较差...)
public static void main(String[] args) {
int year = 1900;
while (year <= 2100 ){
System.out.println(year + " Is "+ ((year % 4 == 0)? "" : "not")+" a Leap Year");
year++;
}
}
您正在滥用while循环。while循环的原理是做同样的事情,直到条件成立为止。
所以这 :
while(condition){ doSomething()}
可以转换为:条件为true时,我将继续执行doSomething();如果条件为true,我将继续执行。
在你原来代码中的条件year <= 2100 && (year % 4 == 0)
,因此是真的只有一年较小或等于2100和年度模4等于0。而这是假的于是退出循环第二个条件。
看看我如何在循环中使用IF ELSE语句?循环贯穿了所有的年份,对于每个年份,我们都测试这是否不是a年。
您确定年份是否为a年的方式尚不完整。维基百科提出了一个好的算法:
if year is divisible by 400 then
is_leap_year
else if year is divisible by 100 then
not_leap_year
else if year is divisible by 4 then
is_leap_year
else
not_leap_year
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句