If the user enters a numerical value 1-12 for a month, how can I change my code below so that it outputs the maximum number of days for that month entered by user.
import java.util.*;
public class LastDay {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
GregorianCalendar cal = new GregorianCalendar();
int myMonth;
System.out.println("Enter the month number (1-12): ");
myMonth = scanner.nextInt();
System.out.println("Maximum number of days is: " + Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
}
}
At the moment it outputs the max number of days for month we're currently in (March). I would like for it to do it for myMonth value entered by user.
At the moment it outputs the max number of days for month we're currently in (March).
Calendar.getInstance()
returns current time, thus current month. You should:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, myMonth - 1);
int actualMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
You must set the month before:
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH, myMonth - 1);
System.out.println("Maximum number of days is: " + cal.getActualMaximum(Calendar.DAY_OF_MONTH));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With