如何根据用户的输入实例化日历?我试过了:
Calendar cal = new GregorianCalendar(2011, Calendar.t.getMonth(month), 1);
但是没有成功。
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;
}
}
也许是更实用的方式呢?谢谢。
最佳答案
您需要在月份中添加1,因为它从0开始而不是1:
int month = sc.nextInt();
Calendar cal = new GregorianCalendar(2011, month + 1, 1);
或者,如果您希望用户插入字符串而不是数字值,则可以执行以下操作:
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);
关于java - 自定义gregoriancalendar月,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8212240/