我必须保持程序基本,没什么太花哨的。这是我的问题: 当我输入日期“11/31/2013”时,它返回“30天常规月份的日输入错误”。我理解这意味着我的If / Else语句和/或我的布尔表达式的结构存在问题。但我似乎无法弄清楚问题所在。感谢任何帮助,谢谢。
这是我的计划:
import java.util.Scanner;
public class DateValidation {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String date;
System.out.println("Please enter a date in the following format: mm/dd/yyyy ");
date = keyboard.next();
int month = Integer.parseInt(date.substring(0, 2));
int day = Integer.parseInt(date.substring(3, 5));
int year = Integer.parseInt(date.substring(6, 10));
boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));
boolean thirtyMonth = (month == 9 || month == 4 || month == 5 || month == 10);
boolean regMonth = (month == 1 || month == 3 || month == 6 || month == 7 || month == 8 || month == 11 || month == 12);
if ((month <= 0) || (day <= 0) || (day >= 32)) {
System.out.println("You entered an incorrect month or day value");
}
if ((month == 2) && (isLeapYear == true) && (day > 0) && (day <= 29)) {
System.out.println("it's a leap year - the date is " + date);
System.exit(0);
} else if ((month == 2) && (isLeapYear == false) && (day > 0) && (day <= 28)) {
System.out.println("it's not a leap year - the date is " + date);
System.exit(0);
} else if (month == 2) {
System.out.println("Your input is invald. Non leap-years only have 28 days");
System.exit(0);
}
if ((thirtyMonth == true) && (day > 0) && (day <= 30)) {
System.out.println("This is a valid date for a 30 day month - here is the date " + date);
System.exit(0);
} else if ((thirtyMonth == true) && (day < 0) || (day >= 31)) {
System.out.println("Incorrect day input for a regular month with 30 days");
System.exit(0);
}
if ((regMonth) && (day > 0) && (day <= 31)) {
System.out.println("This is a valid date for a regular month with 31 days - here is the date " + date);
System.exit(0);
} else if ((regMonth) && (day < 0) && (day >= 32)) {
System.out.println("Incorrect day input for a regular month with 31 days");
System.exit(0);
}
}
}
答案 0 :(得分:2)
4月,6月9月和11月为30天月
boolean thirtyMonth = (month == 9 || month == 4 || month == 5 || month == 10);
应该是
boolean thirtyMonth = (month == 9 || month == 4 || month == 6 || month == 11);
boolean regMonth = (month == 1 || month == 3 || month == 5 ||month == 7 || month == 8 || month == 10 || month == 12);
答案 1 :(得分:1)
变化
} else if ((thirtyMonth == true) && (day < 0) || (day >= 31)) {
到
} else if (thirtyMonth && (day < 0 || day >= 31)) {