需要帮助方法调用程序 - 年份的天数

时间:2014-11-14 20:43:14

标签: java

基本上我在我的程序中间涉及要求用户输入日,月和年,并且基于该条目我应该创建一个计算一年中天数的方法,但是当然,我需要一种方法来定义每个月的天数,以及一种确定它是否是闰年的方法。我已经建立了我的方法,用户输入,但现在我有方法/返回问题。以下是我到目前为止的情况:

import java.util.Scanner;

public class DayNumber{

public static void main(String[] args){
  int year;
  int month;
  int day;

  Scanner keyboard = new Scanner(System.in);
  System.out.print("Enter the date's year (0001 - 9999): ");
  year = keyboard.nextInt();
  System.out.print("Enter the date's month (1 - 12): ");
  month = keyboard.nextInt();
  System.out.print("Enter the date's day (1 - 31): ");
  day = keyboard.nextInt();
}

public static int numberOfDays(int day, int month, int year){
  int numberOfDays;
  return numberOfDays;
}

public static int daysInMonth(int month, int year){
  int daysInMonth;

  if (month ==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12){

     month = 31;}

  if (month ==4 || month ==6 || month==9|| month==11){

     month = 30;}

  else if (month ==2){  

     if (){
     }
  }

  return daysInMonth;
}

public static boolean isLeapYear(int year){
  if (((year%4 == 0) && (year%100 != 0)) || (year%400 ==0)){
     return true;
  }  
  else{
     return false;
  }
}

}

我将不胜感激任何建议或提示。我是Java新手,所以请继续前进吧!感谢。

2 个答案:

答案 0 :(得分:1)

有几种不同的方式。你的看起来很好。

但我最喜欢的是这条小小的一线:

daysInMonth = (month === 2) ? (28 + isLeapYear) : 31 - (month - 1) % 7 % 2;

如果你问自己:为什么%7%2?

嗯,你已经注意到,从8月开始,模式被还原,这就是我们在这里做的事情。我们说在0到6之间它是正常的,那么如果它是7(7%7 = 0)我们将从开始回来)。然后%2将在0 - 1之间交替。

希望我清楚明白

答案 1 :(得分:0)

虽然你的问题不明确。我试着理解,这是我的理解:

  1. 输入日期
  2. 显示月中的天数
  3. 显示年份是否为闰年
  4. 这是我要做的事情

    Class MyDateHomework {
      public static boolean isLeapYear(int year) { 
        //put logic to find leapyear
      }
      public static int daysInMonth(int month, int year) {
        if(month == 2) {
          return isLeapYear(year) ? 28 : 29;
        }
        //put logic to find days in month
      }
      public static void main(String[] args) {
        //take input and call method to do homework
      }
    }