How do I make this code simpler? [Java Calendar]

+2 votes
asked Nov 11 by Mikhaela (140 points)
public static void main(String ... args)
{
Scanner sc = new Scanner(System.in);

int given;

do 
{

System.out.print("Enter month in number format [1-12]: ");
given = sc.nextInt();
System.out.println();
} while(given > 12 || given <= 0);

switch(given)
{
case 11:

System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat");

for(int y = 1; y <= 1; y++)

{

for (int x = 1; x <=31 ; x++) 

{

System.out.print(x + "\t");
if(x % 7 ==0)
Syst
em.out.println();

}

}

break;

Does anyone have any idea how to format the other months without using calendar class or any fancy code and just pure nested loops? Thank you. 

1 Answer

+1 vote
answered 6 days ago by zemiak (490 points)
edited 5 days ago by zemiak
static void printMonth() {
    String month = "Sun\tMon\tTue\tWed\tThu\tFri\tSat\n";
    // TO DO: start print the month in the correct column
    int column=4;
    month += "\t".repeat(column-1);
    
    for (int day=1, dayOfweek=column;  day<=31;  day++, dayOfweek++) {
        month += day +"\t";
        if (dayOfweek == 7) {
            dayOfweek = 0;
            month += "\n";
        }
    }
    System.out.println(month);
  }
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...