如何使这个Java闰年程序循环?

时间:2015-03-28 16:36:55

标签: java

我必须制作一个程序,告诉你一年是否是闰年。我已经完成了程序的基本功能,但是我希望它能够询问用户是否要再次执行整个操作(如果他们输入yes,它将重复该程序。如果他们输入no,程序将会终止)。我最好使用while循环,但我无法弄清楚如何做到这一点。任何帮助表示赞赏。

System.out.println("This program will let you enter a year and it will tell you" +
        " if it is a lear year");
int lyear;

Scanner scan = new Scanner(System.in);

System.out.println("Enter a valid gregorian year(greater than 1581): ");
lyear = scan.nextInt();

    boolean LeapYear = ((lyear % 4 == 0) && (lyear % 100 != 0) || (lyear % 400 == 0));

    if (lyear < 1582)
    {
        System.out.println("That is not a gregorian year"); 
    }
    else if (LeapYear)
    {
        System.out.println("That is a leap year"); 
    }
    else
    {
        System.out.println("That is not a leap year"); 
    }
}

2 个答案:

答案 0 :(得分:0)

创建一个函数checkLeapYear(),并将当前代码复制到其中。

现在写一个while循环:

boolean repeat = true;

while (repeat) {
  checkLeapYear();

  //prompt user to enter yes/no if they want to run again
  String answer = ...

  repeat = answer.equalsIgnoreCase("yes");
}

答案 1 :(得分:0)

您可以尝试继续使用以下代码段 -

while(scan.hasNext()){
   line = scan.readLine();
   if(line.equalsIgnoreCase("yes"){
    continue;
   }esle{
    try{
       int number = Integer.parseInt(line);
    }catch(NumberFormatException nfe){}
   }
}