Question

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.

Was it helpful?

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);

OTHER TIPS

Use Joda Time instead of native Java GregorianCalendar. Much, much better!

 // From Joda Time documentatio
 // setup date object for midday on Christmas 2004
 Chronology chrono = GregorianChronology.getInstance();
 DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0, chrono);

For every enum, Java has a valueOf(String) static function, that convert a String to the proper enum. Unfortunately, the constants of the Calendar class such as Calendar.JANUARY are constants and not enum. The best for you could be to build an enum with name of months, connect those months to the Calendar constants, and then, after puting to uppercase the input of the user, use the valueOf function.

With code :

public enum Months {

    JANUARY (0),
    FEBRUARY (1),
    MARS (2) // and so on

    private int value;

    test(int value){
        this.value = value;
    }
}

And in your class, have a function like this one :

private int monthFromString(String userInputMonth) {
   return Months.valueOf(userInputMonth);
}

GregorianCalendar is not meant to be instantiated directly (read the javadocs), use Calendar.getInstance() instead, and assign values with set(int...) methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top