java:使用if语句的有效日期 [英] java: Valid date using if statement
问题描述
我想知道扫描仪运行时怎么可能,要求您输入日期,而您输入的日期无效,它会向您显示错误,然后使您再次输入有效日期?问题是,当我的程序运行时,它要求输入日,月和年,但是如果日期不正确,则跳至月,而无需让用户键入正确的日期.错误的日期,但是idk如何使它引起错误或使您再次键入正确的错误,而不是跳到下一个问题.
I was wondering how is it possible when scanner is running and asking you to type in the date and you type in an invalid date, that it shows u an error and then makes u type in the valid date again? The thing is, when my program runs, it asks to enter day, month and year, but if the day is wrong, is skips to month without letting the user type in the correct date.. I know how to get the program to detect wrong dates but idk how to get it to cause an error or make you type the right one again rather then skipping to the next question..
System.out.println("Enter day for the First date");
Scanner da= new Scanner(System.in);
d=da.nextInt();
date.setDay(d);
推荐答案
您将必须为每个输入变量进行验证和循环
you will have to validate and loop for each input variable
类似
Scanner da= new Scanner(System.in);
d= getDay (da);
private int getDay (Scanner da) {
int day = 0;
while (day <= 0 || day > 31) { // tricky logic required here
System.out.println ("Enter day between 1 and 31");
day = da.nextInt ();
}
return day;
}
漂洗并重复月份和年份
注意
根据月/日的不匹配情况,您可能会有更多的逻辑可以应用,例如2月31日
You will maybe have more logic to apply based upon month/day mis-match e.g. 31 february
这篇关于java:使用if语句的有效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!