0

I am writing a code where i have to display my output similar to a calendar view.

Sun Mon Tue Wed Thu Fri Sat
     1   2*  3   4   5   6  
 7   8   9  10  11* 12* 13  
14* 15* 16* 17  18  19* 20  
21  22  23  24  25* 26* 27  
28* 29  30 

My code is here.

System.out.println("Sun Mon Tue Wed Thu Fri Sat");
int currentDay = 0;
for(int i = 0; i<randDay; i++){
  System.out.print("    ");
  currentDay++;
}
for(int i = 0; i< month.length; i++){
  if(month[i]!=null){
    System.out.printf("%3s" + "*", (i+1));
    currentDay++;
  }else{
    System.out.printf("%3s", (i+1));
    currentDay++;
  } 
   if(currentDay==7){
     currentDay=0;
     System.out.println();
  }

I can't line them up nicely with my code. Can anyone help me with this? This is just part of my code. I can explain the question if there is a need for it.

My output looks like this.

Sun Mon Tue Wed Thu Fri Sat
              1  2  3  4
  5  6  7*  8  9 10 11*
 12* 13 14 15 16 17 18
 19 20 21 22 23* 24* 25
 26 27* 28 29* 30


Sun Mon Tue Wed Thu Fri Sat
                      1  2
  3  4  5*  6  7  8  9*
 10* 11 12 13 14 15* 16
 17* 18* 19 20 21 22 23
 24 25 26* 27 28* 29 30
 31
mhasan
  • 3,703
  • 1
  • 18
  • 37

2 Answers2

2

You number formatting is off, as you can see. You're formatting with 3-place number, and optional *, which means that sometimes the combined width is 3 and sometimes 4. That won't line up.

But format is really:

<2-place number><space or '*'><space or newline>

That is a 3-part format, though you probably should do them separately.

System.out.printf("%2d", i + 1);
System.out.print(month[i] != null ? '*' : ' ');
if (++currentDay < 7) {
    System.out.print(' ');
} else {
    System.out.println();
    currentDay = 0;
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

It looks like you want each day in the calendar to be 3 characters long, with a space in between them. Additionally, it looks like single digits should prefer to be centered, double digits should prefer left aligned, and anything with an asterisk should be left aligned.

First thing I notice is these lines are 4 are 3 characters, respectively.

System.out.printf("%3s" + "*", (i+1));
System.out.printf("%3s", (i+1));

Therefore, anything with an asterisk is going to be 4 characters and anything without will be 3. This alone will cause them to be misaligned.

Instead, I'd opt for %2s instead of 3. You'll also want to conditionally add a space or an asterisk after, depending on if the item isn't null. This ensures they are each 3 characters, and then you can always add a space between each item in the loop.