我在尝试编写正确的代码时遇到问题,以测试键盘中的字符串是否包含正确月份的有效日期,每个特定月份的天数以及格式mm / dd / yyyy以及闰年的调整是我到目前为止所做的,我不认为我甚至接近,但任何帮助将不胜感激。提前致谢
/* read a date from a string from the keyboard to determine if date is in mm/dd/yyyy format.
*/
import java.util.Scanner;
public class DateFormat
{
public static void main(String [ ] args)
{
Scanner inp = new Scanner(System.in);
System.out.println("Enter the date in mm/dd/yyyy format. ");
int mm;
int dd;
int yy;
int date = inp.nextInt();
boolean isLeapYear;
if ((mm <1) && (mm >12))
System.out.println( date + " is not valid month must be between 1 and 12.");
if (( mm = 4) && ( dd <=30 ))
System.out.println( date + " is a valid date.");
}
else
System.out.println(date + " is not valid date must have 30 or less days. ");
if (date = mm + "/" + dd + "/" + yy);
System.out.println( date + " is a valid date format. ");
}
else{
System.out.println( date + " is not valid must be in dd/mm/yyyy format.");
if (yy %100 ==0) {
if (yy % 400 ==0){
isLeapYear = true;
}
else{
isLeapYear = false;
}
}
else{
if (yy %4 ==0){
isLeapYear = true;
}
else{
isLeapYear = false;
if (isLeapYear)
if ((mm ==2) && (dd <= 29 ))
System.out.println(date + " is a valid date.");
}
else{
System.out.println( date + "is not valid month must have 29 days or less.");
if ((mm ==2) && (dd<=28))
System.out.println( date + " is a valid date.");
}
else{
System.out.println( date + "is not valid must have 28 days or less. ");
答案 0 :(得分:4)
我认为这会有所帮助: http://www.javadb.com/check-if-a-string-is-a-valid-date
基本上,您不需要编写代码来检查日期是否有效。例如,您可以使用java.text包中的SimpleDataFormat类。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Valid? " + isValidDate(scanner.nextLine()));
}
private boolean isValidDate(String inDate) {
if (inDate == null)
return false;
//set the format to use as a constructor argument
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
if (inDate.trim().length() != dateFormat.toPattern().length())
return false;
dateFormat.setLenient(false);
try {
//parse the inDate parameter
dateFormat.parse(inDate.trim());
}
catch (ParseException pe) {
return false;
}
return true;
}