0

How to calculate no of days in a month? User to enter the no of the month. I have written a piece of code for the above, and want to know if its appropriate.

public class Exercise{


    public static void main(String[] args) {

        System.out.print("Input a month number:");
        Scanner scan ;
        int month = 1; int monthName = 1;
        while(month < 12 && month > 0) {
            scan = new Scanner(System.in);
            monthName = scan.nextInt();

            month= monthName-1;
            DateFormat df = new SimpleDateFormat("MMM", Locale.US);     
            Calendar mycal = Calendar.getInstance();
            mycal.set(Calendar.YEAR, 2017);
            mycal.set(Calendar.MONTH, month);
            int numDays = mycal.getActualMaximum(Calendar.DATE);
            System.out.println(" The no of days in the month of is "+ " "+ numDays);
        } 

    }
}
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
  • 3
    Why do you think it's not appropriate? – Mritunjay Sep 20 '17 at 03:59
  • Did you try executing it yourself? https://ideone.com/aFAf3t – Naman Sep 20 '17 at 04:00
  • I'm not sure what are your try to do. – Ravi Sep 20 '17 at 04:01
  • 1
    Yes, it is correct if you want this for the current year as the difference will be when there is a leap year. – Dev Sep 20 '17 at 04:04
  • You should not hardcode the year 2017 but the current year (it might be a leap year which causes a difference in February). – Meno Hochschild Sep 20 '17 at 04:09
  • @MenoHochschild maybe it's not _meant_ to give the month lengths for the current year but only for 2017? We haven't been told the requirements (:->) – Kevin Anderson Sep 20 '17 at 04:15
  • (1) No need to create a scanner for each iteration, just one before the loop. (2) Don’t declare a variable until you need it; declare `monthName` inside the loop. (3) If you’re not using `df` for anything, delete that line. (4) `Calendar` is long outdated. You want the `YearMonth` class and its `lengthOfMonth` method. – Ole V.V. Sep 20 '17 at 07:26

0 Answers0