1
import java.util.*;
public class LeapYear
{
    public static void main (String[]args)
    {
        Scanner scan= new Scanner (System.in);
        System.out.println("Please enter in the year");
        int year=scan.nextInt();
        if (year % 4 ==0)
        {
            { 
                if (year % 100 ==0);
                else 
                    System.out.println("The year,"+year+",is a leap year!");
            }
            if(year % 400==0)
                System.out.println("The year, "+year+",is a leap year!");
        }
        else
            System.out.println("The year, "+year+",is not a leap year!");
    }
}

嘿大家!以上是我的闰年程序代码 - 它似乎运行良好,除非我输入 3000 或 300 之类的数字,JVM 只是停止并关闭终端窗口。有人可以指导为什么它不接受这些数字(另外,请原谅我的代码格式不正确 - 我是新手,正在尽我所能)注意:当我显示所有正确的答案时测试 1900、1996、2004、164 和 204 作为年份。它根本不接受 300 或 3000。再次感谢!

4

3 回答 3

3

检查以下几行:

if (year % 100 ==0);
else 

300 % 100 == 0,没有输出。

于 2014-10-01T01:27:59.167 回答
1

如果你这样做,你可以使你的代码更简洁:

if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
  System.out.println("The year,"+year+",is a leap year!");
} else {
  System.out.println("The year, "+year+",is not a leap year!");
}

另外,请注意,这个计算闰年的公式只适用于“1583”之后的年份。

于 2014-10-01T01:35:16.497 回答
1

您要求我们原谅您的格式,但正是您的格式导致您错过了问题。特别是当您刚开始时,如果您对格式非常勤奋,您会发现了解正在发生的事情最有帮助。建议:始终包含大括号,即使它们是可选的,并且始终提供每个“if”语句的“else”部分。因此:

if (condition) {
    action;
} else {
    alternative action;
}

在您的情况下,您将在第 11 行和第 12 行中看到语法正确的代码,但很可能不是您的意思。第 11 行的左大括号似乎不合适,第 12 行末尾的分号只是代替了条件为真时将发生的“动作”。

if ((year % 4) == 0) {
    // could be a leap year
    if ((year % 100) == 0) {
        // could be a leap year too
        if ((year % 400) == 0) {
            println("yes, this is a leap year ... divisible by 4, 100, AND 400");
        } else {
            // not a leap year ... divisible by 4 and 100, but NOT 400
        }
    } else {
        println("yes, this is a leap year ... it's divisible by 4 but not 100");
    }
} else {
    // absolutely not a leap year
}
于 2014-10-01T01:39:53.060 回答