Java: Please complete the code USING THIS FORMAT to: 1). align the \'1\' under t
ID: 3590914 • Letter: J
Question
Java: Please complete the code USING THIS FORMAT to: 1). align the '1' under the correct day of the week. 2).align the columns correctly under the days of the week import java.util.Scanner; public class Mycode { public static void main(String[] args) { int firstDay; // day of week (0-6) the 1rst is on int numDaysInMonth; // 28-31 int day = 1; // counts from 1 to numDaysInMonth Scanner input = new Scanner(System.in); int currentDay; // current day of week being printed as a number 0-6 System.out.print ("Enter the first day of the week (0-6, 0=sunday, etc.): "); firstDay = input.nextInt(); System.out.print ("Enter the number of days in the month: "); numDaysInMonth = input.nextInt(); currentDay = 0; // start printing at Sunday // TODO: Align the '1' under the correct day of the week // TODO: Align the columns correctly under the days of the week // you may find printf() helpful // Print the days System.out.println("Su Mo Tu We Th Fr Sa"); // Print one day while (day <= numDaysInMonth) { // printing a value System.out.print(day); System.out.print(" "); day++; currentDay++; if (currentDay == 7) { System.out.println(""); currentDay = 0; } } } }
Explanation / Answer
Please find my implementation.
import java.util.Scanner;
public class Mycode {
public static void main(String[] args) {
int firstDay; // day of week (0-6) the 1rst is on
int numDaysInMonth; // 28-31
int day = 1; // counts from 1 to numDaysInMonth
Scanner input = new Scanner(System.in);
int currentDay; // current day of week being printed as a number 0-6
System.out.print ("Enter the first day of the week (0-6, 0=sunday, etc.): ");
firstDay = input.nextInt();
System.out.print ("Enter the number of days in the month: ");
numDaysInMonth = input.nextInt();
input.close();
currentDay = 0; // start printing at Sunday
// TODO: Align the '1' under the correct day of the week
// TODO: Align the columns correctly under the days of the week
// you may find printf() helpful
// Print the days
System.out.println("Su Mo Tu We Th Fr Sa");
while(currentDay <= day) {
currentDay++;
System.out.print(" ");
}
// Print one day
while (day <= numDaysInMonth) {
// printing a value
System.out.print(day);
System.out.print(" ");
day++;
currentDay++;
if (currentDay == 7) {
System.out.println();
currentDay = 0;
}
}
}
}
/*
Sample run:
Enter the first day of the week (0-6, 0=sunday, etc.): 3
Enter the number of days in the month: 31
Su Mo Tu We Th Fr Sa
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
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.