First of, I have been searching to find anything close to my question but I couldn't find anything. I am not a very good programmer, I have just started to play with it a little, and my interest for it is growing a lot.
I was thinking if I could make a basic program with basic and easy understandable language, to a month and days "calculator".
Like if I have a sysout print which says: Write month number, and I'll type in 11, and then write a day number in the month and someone writes 27 it will say date correct!
But if it asks me for month and I'll type 6, as June and I write in 31 as days it will print which would say Month 6 doesn't have day 31.
I want to keep it simple so I understand like basic language not too hard! I'm just a fresh starter!
Thanks for all help.
If you just want to get the job done, I'd suggest you go have a look at the Calendar API or perhaps JodaTime.
If you're more interested in learning how to do it yourself, here's one suggestion for an approach:
Hard-code an array like
int[] daysInMonths = { 31, 27, 31, ... };
and then check using something along the following lines:
// Get month and day from user
Scanner s = new Scanner(System.in);
int month = s.nextInt();
int day = s.nextInt();
int monthIndex = month - 1; // since array indices are 0-based
if (1 <= day && day <= daysInMonths[monthIndex])
print ok
else
print does not exist
This program should get you going...
import java.util.*;
class Date {
public static void main(String[] args) {
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
System.out.print("Enter a month number and a day number (separate using \';\':_");
Scanner sc = new Scanner(System.in).useDelimiter(";");
int month = sc.nextInt();
int day = sc.nextInt();
sc.close();
System.out.println((day == days[month - 1]) ? "Date correct!" : "Date incorrect: Month " + month + " does not have day " + day);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With