java求前n天,但是不允许使用Java中任何与日期有关的类或方法输入格式: 在一行中输入年月日的值以及n的值。 输出格式: 当输入的年、月、日以及n的值非法时,输出“Wrong Format”; 当输入数据合法时,输出“n days ago is:年-月-日”
时间: 2024-05-05 21:20:53 浏览: 9
以下是一个可能的实现方式:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取年、月、日和n的值
int year = scanner.nextInt();
int month = scanner.nextInt();
int day = scanner.nextInt();
int n = scanner.nextInt();
// 判断输入是否合法
if (!isValidDate(year, month, day) || n < 0) {
System.out.println("Wrong Format");
return;
}
// 计算前n天的日期
for (int i = 0; i < n; i++) {
day--;
if (day == 0) {
month--;
if (month == 0) {
year--;
month = 12;
}
day = daysInMonth(year, month);
}
}
// 输出结果
System.out.printf("%d days ago is:%d-%02d-%02d", n, year, month, day);
}
// 判断是否是合法的日期
private static boolean isValidDate(int year, int month, int day) {
if (year < 1 || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
return false;
}
return true;
}
// 计算指定年月的天数
private static int daysInMonth(int year, int month) {
switch (month) {
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
// 判断是否是闰年
private static boolean isLeapYear(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return true;
} else {
return false;
}
}
}
```
该实现中,首先读取输入的年、月、日和n的值,然后判断输入是否合法,如果不合法则输出错误信息并结束程序。如果输入合法,则通过循环计算前n天的日期,最后输出结果。其中,判断日期是否合法使用了isValidDate方法,计算指定年月的天数使用了daysInMonth方法,判断是否是闰年使用了isLeapYear方法。这些方法都是手动实现的,没有使用Java中任何与日期有关的类或方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)