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

Time:10-06

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?

CodePudding user response:

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]   ".");
}

CodePudding user response:

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   "."));

CodePudding user response:

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.

  • Related