Search code examples
javaoopgregorian-calendar

Custom gregoriancalendar month


How do I instantiate the calendar depending on the input of the user? I've tried:

Calendar cal = new GregorianCalendar(2011, Calendar.t.getMonth(month), 1);

But didn't do the trick.

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Scanner;

public class Test {
    public static void main(String[] args){
        Test t = new Test();
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a month: ");
        String month = sc.next();

        Calendar cal = new GregorianCalendar(2011, Calendar.JANUARY, 1);

        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.print("There are "+days+" days in "+month+".");
    }
    private String getMonth(String month){
        return month;
    }
}

Or maybe a more practical way of doing it? Thanks.


Solution

  • You need to add one to the month since it starts from 0 not 1:

    int month = sc.nextInt();
    Calendar cal = new GregorianCalendar(2011, month + 1, 1);
    

    or if you want the user to insert a String not a numerical value, then you can do something like:

    String month = sc.nextLine();
    int iMonth = -1;
    if(month.equalsIgnoreCase("January"))  iMonth = 0;
    else if(month.equalsIgnoreCase("February")) iMonth = 1;
    // and so on ...
    Calendar cal = new GregorianCalendar(2011, iMonth, 1);