增加一天的算法
import java.util.Scanner;
/**
* @author Jackie
* 日期加一
*/
public class DateAddOneTest {
int day;
int month;
int year;
boolean leapYear;
/*定义带有年月日的构造函数*/
DateAddOneTest(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
/*判断是否为闰年*/
public boolean isLeapYear(int year){
return ((year%4 == 0 && year%100 != 0) || year%400 == 0);
}
public static void main(String[] args){
/*从控制台输入一个日期,一次输入年-回车月-回车-日回车*/
System.out.println("Please enter the year,the month and the day:");
Scanner scanner = new Scanner(System.in);
System.out.print("year:");
int year = scanner.nextInt();
System.out.print("month:");
int month = scanner.nextInt();
System.out.print("day:");
int day = scanner.nextInt();
/*取输入的“日”变量*/
/*检验是否有效 */
if(day <= 0 || day >=32)
{
System.out.println("Wrong day below or equals zero or overflow.");
//如果输入日期有错误,则退出。
System.exit(0);
}
DateAddOneTest addOne = new DateAddOneTest(year , month , day);
//得到二月
switch(month){
case 2:
//判断是否为闰年
if(addOne.isLeapYear(year) == true){
if(day < 29) day++;
else if(day == 29) { month++; day = 1; }
else {System.out.println("Day error.");}
}
else if(day < 28)
{day++;}
else if(day == 28) { month++; day = 1;}
else {System.out.println("Day error.");}
}
System.out.println(year + "年/" + month + "月/" + day + "日");
System.out.println(day + "日/" + month + "月/" + year + "年");
System.out.println(month + "月/" + day + "日/" + year + "年");
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(day < 31) day++;
else if(day ==31) { month++; day = 1; }
else {System.out.println("Day error.");}
System.out.println(year + "年/" + month + "月/" + day + "日");
System.out.println(day + "日/" + month + "月/" + year + "年");
System.out.println(month + "月/" + day + "日/" + year + "年");
break;
case 4:
case 6:
case 9:
case 11:
if(day < 30) day++;
else if(day ==31) { month++; day = 1; }
else {System.out.println("Day error.");}
break;
default :
System.out.println("Input error!!!");
break;
}
}
}