Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Months and days?

Tags:

java

time

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.

like image 630
Sebastian Avatar asked Jun 23 '26 09:06

Sebastian


2 Answers

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
like image 149
aioobe Avatar answered Jun 26 '26 00:06

aioobe


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);
    }
}
like image 27
fireshadow52 Avatar answered Jun 25 '26 23:06

fireshadow52



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!