7-1 sdut-JAVA-Date Validation
分数 15
全屏浏览
切换布局
作者 马新娟
单位 山东理工大学
Write a Java application program to accept three numeric values from the end user namely day, month and year. Your program should report whether or not these values constitute a valid date. You should modify your solution so that you accept the values from the end user in your main() method and then pass these values to another method titled validateDate(). The validateDate() method will return true to your main() method if the values constitute a valid date otherwise it will return false. Your main() method should display a message stating whether or not the values constitute a valid date.
Input Specification:
accept three numeric values from the end user namely day, month and year.
Output Specification:
display a message stating whether or not the values constitute a valid date.
Sample Input:
28 2 2023
Sample Output:
valid date
Sample Input:
30 2 2023
Sample Output:
invalid date
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); int day =in. nextInt(); int month =in.nextInt(); int year=in.nextInt(); in.close(); if(validatedate(day,month,year)) { System.out.println("valid date"); } else { System.out.println("invalid date"); } } public static boolean validatedate(int day,int month,int year) { if(month<1||month>12) { return false; } if(day<1||day>31) { return false; } if(month==4||month==6||month==9||month==11) { if(day==31) { return false; } } if(month==2) { if(day>29){ return false; } if(day==29&&!isLeapYear(year)) { return false; } } return true; } public static boolean isLeapYear(int year) { return(year%4==0&&year%100!=0)||(year%400==0); } }