w3resource

Java: Reads a date and prints the day of the date

Java Basic: Exercise-225 with Solution

Write a Java program that reads a date (from 2004/1/1 to 2004/12/31) and prints the day of the date. Jan. 1, 2004, was Thursday. Note that 2004 is a leap year.

Visual Presentation:

Java Basic Exercises: Reads a date and prints the day of the date.

Sample Solution:

Java Code:

// Importing the Scanner class for user input
import java.util.*;

// Main class named "Main"
class Main {

    // Array to store the number of days in each month
    static int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    // Array to store the names of the days
    static String name[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    // Main method to execute the program
    public static void main(String args[]) {
        // Creating a Scanner object for user input
        Scanner in = new Scanner(System.in);

        // Prompting the user to input month and date (0 0 to exit)
        System.out.println("Input month and date (0 0 to exit)");

        // Infinite loop for continuous input until 0 0 is entered
        for (;;) {
            // Reading the input values for month and date
            int m = in.nextInt(), d = in.nextInt();

            // Checking for the exit condition
            if (m == 0 && d == 0) break;

            // Calling the solve method and printing the result
            System.out.println(solve(m, d));
        }
    }

    // Method to determine the day of the week based on the given month and date
    static String solve(int month, int date) {
        // Setting the initial day to Wednesday (index 3 in the 'name' array)
        int cur = 3;

        // Calculating the day index for the given month and date
        for (int i = 0; i < month - 1; i++) {
            cur += days[i];
        }
        cur += date - 1;

        // Returning the name of the day based on the calculated index
        return name[cur % 7];
    }
} 

Sample Output:

Input month and date(o o to exit)
9
15
Name of the day:
Wednesday

Flowchart:

Flowchart: Reads a date and prints the day of the date.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous:Write a Java program to test the followings.
Next: Write a Java program to print mode values from a given a sequence of integers. The mode value is the element which occurs most frequently. If there are several mode values, print them in ascending order.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/basic/java-basic-exercise-225.php