How to print the day numbers of each month using Array, String and byte?

Asked

Viewed 955 times

1

I’m trying this code, but it doesn’t work.

public class MesDias {

    public static void main(String[] args) {

        // Array String byte
        String Mes = {Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez};
        byte[] Dias = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        for (int x=0; x<Mes.length(); ++x)
        for (int y=0; y<Dias.length; ++y)

        System.out.println(Mes[x] + " " + Dias[y]); 

    }
}
  • 3

    Is it really necessary to do this? Why not use native classes that do this?

  • Are the months in Portuguese or English? "Feb", "Apr", "May", "Aug" and "Dec" are in English, "Set" and "Out" are in Portuguese.

  • Yeah, months are mixed. I’ll fix it. Thanks, @Victor Stafusa

2 answers

3

You can use the package classes java.time.* to obtain the number of days of all months of the year, for example:

final int year = 2017;

for(Month month : Month.values()){

    LocalDate date = LocalDate.of(year, month, 01);
    int numberOfDays = date.lengthOfMonth();
    String monthName = month.getDisplayName(TextStyle.FULL, new Locale("pt", "BR"));

    System.out.println(monthName + " tem " + numberOfDays + " dias.");
}

Running on IDEONE

  • Thank you, @Renan I’m just getting started.

1


There are some errors in this code. The first array is not declared as an array and the elements are not in quotes. To show each respective month with the day, do not need to make a nested.

Ex:

public class Datas {

    public static void main(String[] args) {


        // Array String byte
        String[] Months = { "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez" };
        byte[] Days = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        for (int x = 0; x < Months.length; ++x)
                System.out.println(Months[x] + " " + Days[x]);
    }

}
  • Thank you, @Júlio César Baltazar

  • For nothing, I’m happy to help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.