Epicskylegend
Epicskylegend

Reputation: 41

How Would I Create a Loop to Display the Months and Days in Each Month?

public class Array {

    public static void main(String args[]) {
        String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        System.out.println("There are a total of " + daysInMonth[0] + " days in the month of " + months[0] + ".");
    }

}

Instead of printing to the console 12 different times for each one of the months, how could I make my code more efficient and create a loop to print out each of the elements in my arrays?

Upvotes: 1

Views: 1057

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79395

The answer by semicolon is correct and you should accept that. I have written this answer to introduce you to the java.time API.

import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 12; i++) {
            Month month = Month.of(i);
            System.out.println(month.getDisplayName(TextStyle.FULL, Locale.ENGLISH) + " has a maximum of "
                    + month.maxLength() + " days.");
        }
    }
}

Output:

January has a maximum of 31 days.
February has a maximum of 29 days.
March has a maximum of 31 days.
...

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.

Upvotes: 1

Matthew S.
Matthew S.

Reputation: 331

You could create a Map<String, Integer> and then iterate through it.

final Map<String, Integer> months = new HashMap<>();
months.put("January", 31);
months.put("February", 28);
...
months.forEach((k, v) -> System.out.println("There are a total of " + v + " days in the month of " + k + "."));

Upvotes: 0

semicolon
semicolon

Reputation: 545

Try following:

for (int i = 0; i < 12; i++) {
    System.out.println("There are a total of " + daysInMonth[i] + " days in the month of " + months[i] + ".");
}

Upvotes: 3

Related Questions