Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...