Saad Saad - 2 months ago 16
Java Question

Java Program Output

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

Answer

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;
}