Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with different row lengths [duplicate]

I have to output a Julian Calendar in java. I printed out each month, however I am unsure how to fix the row lengths to correspond to each month. For example, February, April, June, September and November do not have 31 days. This is my code so far:

 import java.text.DateFormatSymbols;

 public class testing {

 public void Day() {
   System.out.println();
   for (int i = 1; i <= 31; i++) {
     System.out.println(String.format("%2s", i));
   }
 }
 public void MonthNames() {
   String[] months = new DateFormatSymbols().getShortMonths();
   for (int i =  0; i < months.length; i++) {
     String month = months[i];
     System.out.printf(month + "   ");
     //System.out.printf("\t");       
    }    
  }

  public void ColRow() {
    int dayNum365 = 1;
    int array [][] = new int[31][12];
    System.out.println();
    for (int col = 0; col < 12; col++) {
      for (int row = 0; row < 31; row++) {
        array[row][col] += (dayNum365);
        dayNum365++;
      }
    }

    for (int col = 0; col < array.length; col++) {
     for (int row = 0; row < array[col].length; row++) {
        System.out.printf("%03d", array[col][row]);
        System.out.print("   ");
     }
    System.out.println();
    }
  }

  public static void main(String[] args) {
    testing calendar = new testing();
    calendar.MonthNames();
    calendar.ColRow();
  }
}
like image 320
ellier7 Avatar asked Oct 19 '25 13:10

ellier7


1 Answers

We can create a matrix with a different number of columns for each row (called a jagged matrix) like this:

int[][] months = new int[12][];

months[0] = new int[31]; // January
months[1] = new int[28]; // February, assuming a non-leap year
months[2] = new int[31]; // March
// and so on...

Now, whenever we need to iterate over it, remember to take into account that each row will have a different length:

int dayNum365 = 1;
for (int month = 0; month < months.length; month++) {
    for (int day = 0; day < months[month].length; day++) {
        months[month][day] = dayNum365;
        dayNum365++;
    }
}

All of the above works because a 2D-matrix is nothing but an array of arrays, bear that in mind when working with matrices in Java.

like image 77
Óscar López Avatar answered Oct 22 '25 02:10

Óscar López



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!