自定义公历月份
如何根据用户的输入实例化日历?我已经尝试过:
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;
}
}
或者也许有更实际的方法?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要向月份添加 1,因为它从 0 开始而不是 1:
或者如果您希望用户插入字符串而不是数值,那么您可以执行以下操作:
You need to add one to the month since it starts from 0 not 1:
or if you want the user to insert a String not a numerical value, then you can do something like:
使用 Joda Time 而不是本机 Java GregorianCalendar。好多了,好多了!
Use Joda Time instead of native Java GregorianCalendar. Much, much better!
对于每个枚举,Java 都有一个 valueOf(String) 静态函数,用于将字符串转换为正确的枚举。不幸的是,Calendar 类的常量(例如 Calendar.JANUARY)是常量,而不是枚举。
最适合您的方法可能是构建一个带有月份名称的枚举,将这些月份连接到 Calendar 常量,然后在将用户的输入设置为大写后,使用 valueOf 函数。
使用代码:
在你的类中,有一个像这样的函数:
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 :
And in your class, have a function like this one :
GregorianCalendar
并不意味着直接实例化(阅读 javadocs),而是使用Calendar.getInstance()
,并使用set(int...) 赋值方法。
GregorianCalendar
is not meant to be instantiated directly (read the javadocs), useCalendar.getInstance()
instead, and assign values withset(int...)
methods.