我被这段代码困住了。 问题说
Write a program that reads a string from the keyboard and tests whether it contains a valid date. Display the date and message that indicates whether it is valid. If it is not valid, also display a message explaining why it is not valid.
The input date will have the format mm/dd/yyyy. A valid month value mm must be from 1 to 12 (January is 1). the day value dd must be from 1 to a value that is appropriate for the given moth. September, April, June, and November each have 30 days. February has 28 days except for the leap years when it has 29. The remaining months all have 31 days each. A leap year is any year that is divisible by 4 but not divisible by 100 unless it is also divisible by 400.
这是我到目前为止编写的代码。问题是,无论我输入什么日期,输出总是相同的。你能帮我找出问题所在吗?
import java.util.Scanner;
public class Ch3ProblemNine
{
public static void main(String [ ] args)
{
System.out.println("Enter the date in mm/dd/yyyy format. ");
String date="";
Scanner keyboard = new Scanner(System.in);
int mm = 00;
int dd = 00;
int yy = 0000;
date = keyboard.nextLine();
boolean isLeapYear;
mm=0;
dd=0;
yy=0;
isLeapYear=false;
if(yy%4==0 && (!(yy%100==0) || yy%400==0))
{
isLeapYear=true;
}
if((mm<12) && (mm>1))
{
System.out.println("You have entered an invalid month. Please try again.");
}
if((dd>31 && dd<1))
{
System.out.println("You have entered an invalid day. Please try again.");
}
if((mm==9 && mm==4 && mm==6 && mm==11) && !(dd==31))
{
System.out.println("For the given month, you have entered an invalid day.");
}
if((mm==2 && !(dd<29)) && isLeapYear==false)
{
System.out.println("You have entered an invalid day for the month of February.");
}
if((mm==2 && !(dd<30)) && isLeapYear==true)
{
System.out.println("You have entered an invalid day for the month of February.");
}
else
{
System.out.println("You have entered a valid date in the correct format.");
}
if (isLeapYear){
if((mm==2 && !(dd==29)) && isLeapYear==true)
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.");
}
}
最佳答案
我在几秒钟内找到了这个:http://www.javadb.com/check-if-a-string-is-a-valid-date
您的问题是您没有将“date”字符串放入“mm dd yy”变量中。您的变量永远不会分配任何内容。
关于java - 无法从标准输入读取和验证正确的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7720991/