Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

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

+4 votes
asked Nov 11, 2020 by Mikhaela (160 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 Nov 20, 2020 by zemiak (550 points)
edited Nov 21, 2020 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.
...