使用方法计算闰年

时间:2017-02-19 20:29:15

标签: java class methods leap-year

import java.util.Scanner;

public class LeapYearTester{

   public static void main(String[] args){

      Scanner input = new Scanner(System.in);
      System.out.println("Please enter a year");
      int year_input = input.nextInt();

      // now make a Year object

      Year theYear = new Year(year_input);

      // now check to see if it's a leap year

         if (theYear.isLeapYear())
         System.out.println("That's a leap year!");
         else
         System.out.println("That's not a leap year!");
   }
}


    public class Year
    {
    // declare your instance variables here
    private int theYear;
    private int Year;

    // write your constructor here
    public Year(int y)
    {
    y=Year;
    }
    static boolean isLeapYear(final int Year) {
    return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0);
    //(((Year%4==0) || (Year%400)) && ((!Year%100==0) || (Year%400=0)))  
    }

}    

以上是Main,无法更改。上课时遇到麻烦。

1 个答案:

答案 0 :(得分:1)

除了使用正则表达式添加检查以查看用户是否在1000到2999(包括1000和2999)之间输入有效年份之外,您的原始尝试没有太多修改(我会将其作为任务保留您可以将此代码修改为您认为的有效年份):

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LeapYearTester {
  public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter a year: ");
    String yearInput = "";
    String pattern = "^[12][0-9]{3}$";
    Pattern r = Pattern.compile(pattern);
    //checking is valid year
    while(input.hasNext()){
      yearInput = input.nextLine();
      Matcher m = r.matcher(yearInput);
      if(m.find()) {
        System.out.println("You entered the valid year: " + m.group(0));
        break;
      } else {
        System.out.println("Error: Not a valid year");
        System.out.print("Please enter a year between 1000 and 2999 inclusive: ");
      }
    }

    Year theYear = new Year(Integer.valueOf(yearInput));

    if(theYear.isLeapYear()) { 
      System.out.println("That's a leap year!");
    } else {
      System.out.println("That's not a leap year!");
    }
  }

  public static class Year {
    private int year;

    private Year(int y) {
      year = y;
    }

    private boolean isLeapYear() {
      if (year % 4 != 0) {
        return false;
      } else if (year % 400 == 0) {
        return true;
      } else if (year % 100 == 0) {
        return false;
      } else {
        return true;
      }
    }
  }
}

示例用法:测试闰年

Please enter a year:  2016
You entered the valid year: 2016
That's a leap year!

示例用法:输入无效并测试非闰年

Please enter a year:  3000
Error: Not a valid year
Please enter a year between 1000 and 2999 inclusive:  2015
You entered the valid year: 2015
That's not a leap year!

试试here!