我试图确保我的 nextday 方法可以在用户输入的日期中添加一天,并确保它正确添加 40 天,同时考虑到每月的正确天数和闰年
public nextday() {
for (int count = 1; count < 40; count++)
;
}
public String toDayDateString() // toDayDateString method {
int countDays = 0;
for (int i = 1; i < getMonth(); i++) {
if (i == 2 && checkLeapYr(getYear()))
countDays += 29;
else
countDays += daysPerMonth[i];
}
countDays += date;
String message = String.format("\n", countDays, getYear());
return message;
}
private Boolean checkLeapYr(int inYear) { // check leap year method.
if (getYear() % 400 == 0 || (getYear() % 4 == 0 && getYear() % 100 != 0))
return true;
else
return false;
}
下面是一个菜单,应该允许用户选择输入日期或退出,但该日期未被正确接受。
{
public static void main ( String [] args)
// User selects how they will enter the dates
{
+"(1) Enter the date as MM/DD/YYYY\n"
+"(Any Key) Quit\n";
int input=0;
Date newDate;
do{
String userInput = JOptionPane.showInputDialog(null, menu);
input = Integer.parseInt( userInput);
String outputMessage="";
if ( input = 1)
{
userInput =JOptionPane.showInputDialog(null, "Please enter a date as 02/28/2011");
switch ( input ) // here is where the menu choice will be evaluated
{
case 1 :
token = userInput.split("/");
if (token.length == 3 )
{
newDate = new Date( Integer.parseInt( token[0]),
Integer.parseInt( token[1]), Integer.parseInt( token[2]) );
outputMessage = newDate.toString();
JOptionPane.showMessageDialog(null, outputMessage);
}
break;
case 2:
} while ( input <>1); // this will quit the program when user selects any key other than 1 at the menu.
最佳答案
- 您应该使用
java.text.DateFormat
来解析日期字符串 - 编写自己的日期算术非常容易出错(闰年只是众多异常(exception)之一),最好使用
java.util.Calendar
实现。
至于日期算术,以下是使用 Calendar
完成的方法:
//TODO: parse input string with DateFormat
Date startDate = ... // your parsed date
Calendar cal = new GregorianCalendar();
cal.setTime(startDate);
for (int i = 0; i < 40; i++) {
// add a day
cal.add(Calendar.DATE, 1);
// and get the new result as date
Date date = cal.getTime();
System.out.println(date);
}
如果您需要倒数,请添加负时间量(天、小时等)。
关于java - 如何编写 Java 代码来获取用户输入的任何日期,并列出接下来的 40 天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18986083/