Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

java: Valid date using if statement

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you will have to validate and loop for each input variable

somthing like

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;
}

rinse and repeat for month and year

Note

You will maybe have more logic to apply based upon month/day mis-match e.g. 31 february


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...