+ 2

Why doesn't my date validation code work?

my code doesn't return any value and i have no idea why. My assignment requires me to write a code that accepts date in mm/dd/yyyy format and im required to put leap year in. The problem is, i dont get back any input. Im an amateur ad i dont know what is wrong. Im also allowed to use Case statement but I'm not sure how to implement case. The problem i hvae is, there is no input. Literally non. import java.util.Scanner; public class Question1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in).useDelimiter("/"); System.out.println("Please enter a date in mm/dd/yyyy format: "); String mm = sc.next(); String dd = sc.next(); String yyyy = sc.next(); int month = Integer.parseInt(mm); int day = Integer.parseInt(dd); int year = Integer.parseInt(yyyy); if (month <= 0 && month>12) { System.out.println("invalid month "); } if (year%4 != 0 && month == 02 && day >= 29) { System.out.println("invalid date"); } if (month == 4 && month == 6 && month == 9 && month == 11 && day >= 31) { System.out.println("Invalid day"); } if (month == 1 && month == 3 && month == 5 && month == 7 && month == 8 && month == 10 && month == 12 && day >=32 ) { System.out.println("Invalid day"); } else { System.out.println("Valid date"); } } }

26th Feb 2017, 4:31 AM
Bamdad Goudarzi Moazami
Bamdad Goudarzi Moazami - avatar
2 Antworten
+ 2
You need to trim off the trailing whitespace from yyyy and/or add \n as a delimiter. int month = Integer.parseInt(mm); int day = Integer.parseInt(dd); int year = Integer.parseInt(yyyy.trim()); The program will run once this whitespace is removed. However, you may also want to revisit your logic in your if statements. ie (month == 4 && month== 6 etc) Will never be true. Wrap the months in parentheses and || or them then && the day.
26th Feb 2017, 5:15 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
The Dawg is right. From a real world standpoint: What should happen at : -1/0/1983? If you want to impress whoever is grading that: The leap rule is somewhat more complicated, since Pope Gregory. There is no year 0. The 0 wasn't invented, when the calendar was made. Weird things happen in 1583.
26th Feb 2017, 7:01 AM
1of3
1of3 - avatar