How can I determine what day of the week a given month falls on in Java without using the Calendar Object?











up vote
-1
down vote

favorite












I'm creating a Calendar for my CS class and need to be able to get my calendar months to start on the correct day of the week. My first go at trying to solve this problem looked something like this:



public static int getStartingDay(int month) {

if (month == 1 || month == 10) {

return (18 + 4) % 7;

} else if (month == 2 || month == 3 || month == 11) {

return ((18 + 4 + 3)) % 7;

} else if (month == 4 || month == 7) {

return ((18 + 4 + 6)) % 7;

} else if (month == 9 || month == 12) {

return ((18 + 4 + 5) % 7);

} else if (month == 5) {

return ((18 + 4 + 1) % 7);

} else {

return ((18 + 4 + 1) % 7);

}


I was really happy to see that this was working but when I showed this to my teacher he said it could be done in a much simpler way.



He responded:



"First of all, I want you to recall that I stated we are just concerned with 2018. Therefore, we only need to know what day 2018 started on. From there, we can basically do what we did for the second writing code question on the midterm, where given a day out of 365 for the year, we can determine what day of the week that falls on. This means that all we have left to do it determine what day out of 365 that a given month falls on. This can be done with some addition if we know how many days are in each month. We can just add up all of the previous month's days to get what day our month starts on. "



For the midterm, we were to assume that the year started on Wednesday (3rd day of the week) so my solution looked like this:



Method call : dayOfYear(5); Should return: 0 for Sunday



Public static final int FIRST_DAY_OF_YEAR = 3;

Public static int dayOfTheWeek(int day){

return (firstDay + day –1)%7;

}


Result: 0 (Sunday)



I'm a bit lost on how these two problems are connected. I know the key in my teacher's response was:



"This means that all we have left to do it determine what day out of 365 that a given month falls on." If you could help me understand how to solve this problem, you would be helping me tremendously!



I should also add, We are not allowed to use Java's Calendar object to get this working properly!



Here is my current Project:



 import java.util.*;
public class CalendarReformed {
// Here we can change the size of the calendar
public static final int FIRST_DAY_OF_MONTH = 1;
private static final int SIZE = 7;

public static void main(String args){
Scanner console = new Scanner(System.in);
int day = -1;
int month = -1;
String userSelection;
boolean flag = true;

while (flag){

userMenu();
userSelection = console.next();
if (userSelection.equalsIgnoreCase("e")){
System.out.print("Please enter a date:(mm/dd) ");
String date = console.next();
month = monthFromDate(date);
day = dayFromDate(date);
int highlightSelectedDay = day;
displayCalendar(month, highlightSelectedDay);

} else if (userSelection.equalsIgnoreCase("t")){
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DATE);
month = c.get(Calendar.MONTH)+1;
System.out.println("Today's date: " + month +"/"+ day);
displayCalendar(month,day);
} else if (userSelection.equalsIgnoreCase("n")){
if (day != -1 && month != -1){
day = 1;

month = grabNextMonth(month);
displayCalendar(month,day);
} else{
System.out.print("You must have a month selected to go to next month!n");
}
} else if(userSelection.equalsIgnoreCase("p")){
if (day != -1 && month != -1){
day = 1;

month = grabPreviousMonth(month);
displayCalendar(month, day);
} else {
System.out.print("You must first select a month for previous month to function!n");
}
} else if(userSelection.equalsIgnoreCase("q")){
System.out.print("Now exiting the Calendar programn");
System.out.print("Have a nice day!");
flag = false;
} else {
System.out.print(" *USER ERROR DETECTED* n");
System.out.println("Please make a valid selection from the menu!");
}
}

}

// This method will print the month digit and centers it
public static void drawMonth(int month, int daysToSkip, int maxDays){
System.out.println();
int placeMonth = (SIZE * 3)-4;
for (int space = 1; space <= placeMonth; space++){
printSpaces(1);
}
String monthHolder;
if (month == 1){
monthHolder = "*January*";
} else if(month == 2){
monthHolder = "*February*";
}else if (month == 3){
monthHolder = "*March*";
} else if (month == 4){
monthHolder = "*April*";
} else if (month == 5){
monthHolder = "*May*";
} else if (month == 6){
monthHolder = "*June*";
} else if (month == 7){
monthHolder = "*July*";
} else if (month == 8){
monthHolder = "*August*";
} else if (month == 9){
monthHolder = "*September*";
} else if (month == 10){
monthHolder = "*October*";
} else if (month == 11){
monthHolder = "*November*";
} else {
monthHolder = "*December*";
}
System.out.println(monthHolder);

drawArt();

int start = 1;
while (start <= maxDays) {
if (start == 1) {
drawRow(start, maxDays, daysToSkip);
start += 7 - daysToSkip;
} else {
drawRow(start, maxDays, 0);
start += 7;
}
}

// Displays the top of the calendar border
for (int i = 1; i <= SIZE * 7; i++){
System.out.print("_");
}
}

// This method prints one row of our calendar and applies our | dividers
public static void drawRow(int start,int maxDays, int skip){
for (int top = 1; top <= SIZE * 7; top++){
System.out.print("_");
}
System.out.println();

int printDayNum = start;
String dayTool;

System.out.print("|");
int highlightSelectedDay = -1;
for (int i = 1; i <= 7; i++) {
dayTool = "";
if (i > skip && printDayNum <= maxDays) {
if (highlightSelectedDay == printDayNum) {
dayTool += " ->" + printDayNum++ + "*";
} else {
dayTool += printDayNum++;
}
}

while (dayTool.length() < SIZE - 1){
dayTool += " ";
}

dayTool += "|";
System.out.print(dayTool);
}
int height = SIZE /2;
for (int h = 2; h <= height; h++){
System.out.print("n|");
for (int cell = 1; cell <= 7; cell++){
dayTool = "";
while (dayTool.length() < SIZE -1) {
dayTool += " ";
}
dayTool+="|";
System.out.print(dayTool);
}
}
System.out.println();
}


// This method will display month and the day under the calendar
public static void displayDate(int month, int day){
System.out.println();
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}

// This method grabs the month string from the user input and returns it as an integer
public static int monthFromDate( String date){
int index = date.indexOf("/");
String month = date.substring(0,index);
return Integer.parseInt(month);
}


public static void dateError(String prompt){
System.out.print(prompt+"n");
}
// This method grabs the date which is always after the first two spots of the user date String Returns an int
public static int dayFromDate(String date) {
int index = date.indexOf("/");
String day = date.substring(index + 1);
return Integer.parseInt(day);

}
// Handles the ASCII art above calendar
public static void pattern(){
for (int i = 1; i <= 49/6; i++){
System.out.print("\ 0 / ");
}
System.out.println();
for (int i = 1; i <=49/6; i++){
System.out.print("<(.)> ");
}
System.out.println();
for (int i = 1; i <= 49/6; i++){
System.out.print("/ + \ ");
}
System.out.println();
}

public static void displayCalendar(int month, int day) {
int startDay = getStartingDay(month);
int maxDaysInMonth = getMaxDays(month);
drawMonth(month, startDay, maxDaysInMonth);
displayDate(month,day);
}

public static int getStartingDay(int month) {
if (month == 1 || month == 10) {
return (18 + 4) % 7;
} else if (month == 2 || month == 3 || month == 11) {
return ((18 + 4 + 3)) % 7;
} else if (month == 4 || month == 7) {
return ((18 + 4 + 6)) % 7;
} else if (month == 9 || month == 12) {
return ((18 + 4 + 5) % 7);
} else if (month == 5) {
return ((18 + 4 + 1) % 7);
} else {
return ((18 + 4 + 1) % 7);
}

}
public static int getMaxDays(int month){
int numberOfDays;
if (month == 4 || month == 6 || month == 9 || month == 11){
numberOfDays = 30;
} else if (month == 2){
numberOfDays = 29;
} else
numberOfDays = 31;
return numberOfDays;
}

public static int grabNextMonth(int currentMonth) {
if (currentMonth == 12) // if current month is december
{
return 1; // lets give the user January
} else
return currentMonth + 1; // rest of the time just display the next month
}
public static int grabPreviousMonth(int currentMonth){
if (currentMonth == 1){
return 12;
} else
return currentMonth - 1;
}

// A little more art for top of calendar
public static void drawArt(){
System.out.println(" ____ ___ _ ____ ____ ____| ___ ____ ");
System.out.println("| /__ \ | |____| || | /__ \ | \ ");
System.out.println("|____ / \|____|____| ||__ _|/ \| ");
printChars('_',48);
System.out.println();
for (int i = 1; i <= 2; i+=2){
pattern();
}
}

public static void userMenu(){
System.out.println("Please enter a command: ");
System.out.println("tt["e"] to enter a date and display it");
System.out.println("tt["t"] to get today's date and display the corresponding calendar");
System.out.println("tt["n"] to display the next month");
System.out.println("tt["p"] to display the previous month");
System.out.println("tt["q"] to quit the program");
}

// Method that prints desired chars whenever called
public static void printChars(char ch, int num){
for (int i = 1; i <= num; i++){
System.out.print(ch);
}
}

// Method that can printSpaces when called
public static void printSpaces(int num){
for (int i = 1; i <= num; i++){
System.out.print(" ");
}
}

}









share|improve this question
























  • Putting aside whether the teacher's approach may be simpler, I am frankly mystified by the magic numbers in your answer. What is the significance of 18? 4? Why do the checks test those specific months? (I'm not actually looking for an answer; I'm encouraging you to think about how you would understand this code if you revisited it a year from now, or if this code were to be handed to someone else to maintain).
    – Andy Turner
    Nov 10 at 21:17












  • Thank you. I have really been struggling with this part of the project and was looking everywhere I could for a solution and wound up using a formula I found to calculate the correct days. I guess I was just so happy to see it working that I didn't think about how it was structured.
    – Nicksc831
    Nov 10 at 21:25










  • Focus on working with concepts you think might be useful rather than finding the "right formula" (or magic numbers). Would numberOfDaysInPreceedingMonths += daysIn2018Months[m]; express a concept that is part of the way you think? Programming is a form of expository writing (but often with the supporting details first if they can be expressed simply ex. int daysIn2018Months = { 31, 28, …}).
    – Tom Blodget
    Nov 11 at 2:38










  • It’s a question with a bit of thought-reading in it, something that very few stackoverflowers excel in. If I’m allowed to try anyway, I would guess that you rteacher means that to find the day of week of March 1, you add the number of days in January and the number of days in February to the first day of the year. Similarly for other months.
    – Ole V.V.
    Nov 11 at 6:33










  • For production code you should never use Calendar, it’s poorly designed and long outdated. Instead for a task like this you would use LocalDate from java.time, the modern Java date and time API. For example LocalDate.of(2018, Month.MARCH, 9).getDayOfWeek().
    – Ole V.V.
    Nov 11 at 6:35

















up vote
-1
down vote

favorite












I'm creating a Calendar for my CS class and need to be able to get my calendar months to start on the correct day of the week. My first go at trying to solve this problem looked something like this:



public static int getStartingDay(int month) {

if (month == 1 || month == 10) {

return (18 + 4) % 7;

} else if (month == 2 || month == 3 || month == 11) {

return ((18 + 4 + 3)) % 7;

} else if (month == 4 || month == 7) {

return ((18 + 4 + 6)) % 7;

} else if (month == 9 || month == 12) {

return ((18 + 4 + 5) % 7);

} else if (month == 5) {

return ((18 + 4 + 1) % 7);

} else {

return ((18 + 4 + 1) % 7);

}


I was really happy to see that this was working but when I showed this to my teacher he said it could be done in a much simpler way.



He responded:



"First of all, I want you to recall that I stated we are just concerned with 2018. Therefore, we only need to know what day 2018 started on. From there, we can basically do what we did for the second writing code question on the midterm, where given a day out of 365 for the year, we can determine what day of the week that falls on. This means that all we have left to do it determine what day out of 365 that a given month falls on. This can be done with some addition if we know how many days are in each month. We can just add up all of the previous month's days to get what day our month starts on. "



For the midterm, we were to assume that the year started on Wednesday (3rd day of the week) so my solution looked like this:



Method call : dayOfYear(5); Should return: 0 for Sunday



Public static final int FIRST_DAY_OF_YEAR = 3;

Public static int dayOfTheWeek(int day){

return (firstDay + day –1)%7;

}


Result: 0 (Sunday)



I'm a bit lost on how these two problems are connected. I know the key in my teacher's response was:



"This means that all we have left to do it determine what day out of 365 that a given month falls on." If you could help me understand how to solve this problem, you would be helping me tremendously!



I should also add, We are not allowed to use Java's Calendar object to get this working properly!



Here is my current Project:



 import java.util.*;
public class CalendarReformed {
// Here we can change the size of the calendar
public static final int FIRST_DAY_OF_MONTH = 1;
private static final int SIZE = 7;

public static void main(String args){
Scanner console = new Scanner(System.in);
int day = -1;
int month = -1;
String userSelection;
boolean flag = true;

while (flag){

userMenu();
userSelection = console.next();
if (userSelection.equalsIgnoreCase("e")){
System.out.print("Please enter a date:(mm/dd) ");
String date = console.next();
month = monthFromDate(date);
day = dayFromDate(date);
int highlightSelectedDay = day;
displayCalendar(month, highlightSelectedDay);

} else if (userSelection.equalsIgnoreCase("t")){
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DATE);
month = c.get(Calendar.MONTH)+1;
System.out.println("Today's date: " + month +"/"+ day);
displayCalendar(month,day);
} else if (userSelection.equalsIgnoreCase("n")){
if (day != -1 && month != -1){
day = 1;

month = grabNextMonth(month);
displayCalendar(month,day);
} else{
System.out.print("You must have a month selected to go to next month!n");
}
} else if(userSelection.equalsIgnoreCase("p")){
if (day != -1 && month != -1){
day = 1;

month = grabPreviousMonth(month);
displayCalendar(month, day);
} else {
System.out.print("You must first select a month for previous month to function!n");
}
} else if(userSelection.equalsIgnoreCase("q")){
System.out.print("Now exiting the Calendar programn");
System.out.print("Have a nice day!");
flag = false;
} else {
System.out.print(" *USER ERROR DETECTED* n");
System.out.println("Please make a valid selection from the menu!");
}
}

}

// This method will print the month digit and centers it
public static void drawMonth(int month, int daysToSkip, int maxDays){
System.out.println();
int placeMonth = (SIZE * 3)-4;
for (int space = 1; space <= placeMonth; space++){
printSpaces(1);
}
String monthHolder;
if (month == 1){
monthHolder = "*January*";
} else if(month == 2){
monthHolder = "*February*";
}else if (month == 3){
monthHolder = "*March*";
} else if (month == 4){
monthHolder = "*April*";
} else if (month == 5){
monthHolder = "*May*";
} else if (month == 6){
monthHolder = "*June*";
} else if (month == 7){
monthHolder = "*July*";
} else if (month == 8){
monthHolder = "*August*";
} else if (month == 9){
monthHolder = "*September*";
} else if (month == 10){
monthHolder = "*October*";
} else if (month == 11){
monthHolder = "*November*";
} else {
monthHolder = "*December*";
}
System.out.println(monthHolder);

drawArt();

int start = 1;
while (start <= maxDays) {
if (start == 1) {
drawRow(start, maxDays, daysToSkip);
start += 7 - daysToSkip;
} else {
drawRow(start, maxDays, 0);
start += 7;
}
}

// Displays the top of the calendar border
for (int i = 1; i <= SIZE * 7; i++){
System.out.print("_");
}
}

// This method prints one row of our calendar and applies our | dividers
public static void drawRow(int start,int maxDays, int skip){
for (int top = 1; top <= SIZE * 7; top++){
System.out.print("_");
}
System.out.println();

int printDayNum = start;
String dayTool;

System.out.print("|");
int highlightSelectedDay = -1;
for (int i = 1; i <= 7; i++) {
dayTool = "";
if (i > skip && printDayNum <= maxDays) {
if (highlightSelectedDay == printDayNum) {
dayTool += " ->" + printDayNum++ + "*";
} else {
dayTool += printDayNum++;
}
}

while (dayTool.length() < SIZE - 1){
dayTool += " ";
}

dayTool += "|";
System.out.print(dayTool);
}
int height = SIZE /2;
for (int h = 2; h <= height; h++){
System.out.print("n|");
for (int cell = 1; cell <= 7; cell++){
dayTool = "";
while (dayTool.length() < SIZE -1) {
dayTool += " ";
}
dayTool+="|";
System.out.print(dayTool);
}
}
System.out.println();
}


// This method will display month and the day under the calendar
public static void displayDate(int month, int day){
System.out.println();
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}

// This method grabs the month string from the user input and returns it as an integer
public static int monthFromDate( String date){
int index = date.indexOf("/");
String month = date.substring(0,index);
return Integer.parseInt(month);
}


public static void dateError(String prompt){
System.out.print(prompt+"n");
}
// This method grabs the date which is always after the first two spots of the user date String Returns an int
public static int dayFromDate(String date) {
int index = date.indexOf("/");
String day = date.substring(index + 1);
return Integer.parseInt(day);

}
// Handles the ASCII art above calendar
public static void pattern(){
for (int i = 1; i <= 49/6; i++){
System.out.print("\ 0 / ");
}
System.out.println();
for (int i = 1; i <=49/6; i++){
System.out.print("<(.)> ");
}
System.out.println();
for (int i = 1; i <= 49/6; i++){
System.out.print("/ + \ ");
}
System.out.println();
}

public static void displayCalendar(int month, int day) {
int startDay = getStartingDay(month);
int maxDaysInMonth = getMaxDays(month);
drawMonth(month, startDay, maxDaysInMonth);
displayDate(month,day);
}

public static int getStartingDay(int month) {
if (month == 1 || month == 10) {
return (18 + 4) % 7;
} else if (month == 2 || month == 3 || month == 11) {
return ((18 + 4 + 3)) % 7;
} else if (month == 4 || month == 7) {
return ((18 + 4 + 6)) % 7;
} else if (month == 9 || month == 12) {
return ((18 + 4 + 5) % 7);
} else if (month == 5) {
return ((18 + 4 + 1) % 7);
} else {
return ((18 + 4 + 1) % 7);
}

}
public static int getMaxDays(int month){
int numberOfDays;
if (month == 4 || month == 6 || month == 9 || month == 11){
numberOfDays = 30;
} else if (month == 2){
numberOfDays = 29;
} else
numberOfDays = 31;
return numberOfDays;
}

public static int grabNextMonth(int currentMonth) {
if (currentMonth == 12) // if current month is december
{
return 1; // lets give the user January
} else
return currentMonth + 1; // rest of the time just display the next month
}
public static int grabPreviousMonth(int currentMonth){
if (currentMonth == 1){
return 12;
} else
return currentMonth - 1;
}

// A little more art for top of calendar
public static void drawArt(){
System.out.println(" ____ ___ _ ____ ____ ____| ___ ____ ");
System.out.println("| /__ \ | |____| || | /__ \ | \ ");
System.out.println("|____ / \|____|____| ||__ _|/ \| ");
printChars('_',48);
System.out.println();
for (int i = 1; i <= 2; i+=2){
pattern();
}
}

public static void userMenu(){
System.out.println("Please enter a command: ");
System.out.println("tt["e"] to enter a date and display it");
System.out.println("tt["t"] to get today's date and display the corresponding calendar");
System.out.println("tt["n"] to display the next month");
System.out.println("tt["p"] to display the previous month");
System.out.println("tt["q"] to quit the program");
}

// Method that prints desired chars whenever called
public static void printChars(char ch, int num){
for (int i = 1; i <= num; i++){
System.out.print(ch);
}
}

// Method that can printSpaces when called
public static void printSpaces(int num){
for (int i = 1; i <= num; i++){
System.out.print(" ");
}
}

}









share|improve this question
























  • Putting aside whether the teacher's approach may be simpler, I am frankly mystified by the magic numbers in your answer. What is the significance of 18? 4? Why do the checks test those specific months? (I'm not actually looking for an answer; I'm encouraging you to think about how you would understand this code if you revisited it a year from now, or if this code were to be handed to someone else to maintain).
    – Andy Turner
    Nov 10 at 21:17












  • Thank you. I have really been struggling with this part of the project and was looking everywhere I could for a solution and wound up using a formula I found to calculate the correct days. I guess I was just so happy to see it working that I didn't think about how it was structured.
    – Nicksc831
    Nov 10 at 21:25










  • Focus on working with concepts you think might be useful rather than finding the "right formula" (or magic numbers). Would numberOfDaysInPreceedingMonths += daysIn2018Months[m]; express a concept that is part of the way you think? Programming is a form of expository writing (but often with the supporting details first if they can be expressed simply ex. int daysIn2018Months = { 31, 28, …}).
    – Tom Blodget
    Nov 11 at 2:38










  • It’s a question with a bit of thought-reading in it, something that very few stackoverflowers excel in. If I’m allowed to try anyway, I would guess that you rteacher means that to find the day of week of March 1, you add the number of days in January and the number of days in February to the first day of the year. Similarly for other months.
    – Ole V.V.
    Nov 11 at 6:33










  • For production code you should never use Calendar, it’s poorly designed and long outdated. Instead for a task like this you would use LocalDate from java.time, the modern Java date and time API. For example LocalDate.of(2018, Month.MARCH, 9).getDayOfWeek().
    – Ole V.V.
    Nov 11 at 6:35















up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I'm creating a Calendar for my CS class and need to be able to get my calendar months to start on the correct day of the week. My first go at trying to solve this problem looked something like this:



public static int getStartingDay(int month) {

if (month == 1 || month == 10) {

return (18 + 4) % 7;

} else if (month == 2 || month == 3 || month == 11) {

return ((18 + 4 + 3)) % 7;

} else if (month == 4 || month == 7) {

return ((18 + 4 + 6)) % 7;

} else if (month == 9 || month == 12) {

return ((18 + 4 + 5) % 7);

} else if (month == 5) {

return ((18 + 4 + 1) % 7);

} else {

return ((18 + 4 + 1) % 7);

}


I was really happy to see that this was working but when I showed this to my teacher he said it could be done in a much simpler way.



He responded:



"First of all, I want you to recall that I stated we are just concerned with 2018. Therefore, we only need to know what day 2018 started on. From there, we can basically do what we did for the second writing code question on the midterm, where given a day out of 365 for the year, we can determine what day of the week that falls on. This means that all we have left to do it determine what day out of 365 that a given month falls on. This can be done with some addition if we know how many days are in each month. We can just add up all of the previous month's days to get what day our month starts on. "



For the midterm, we were to assume that the year started on Wednesday (3rd day of the week) so my solution looked like this:



Method call : dayOfYear(5); Should return: 0 for Sunday



Public static final int FIRST_DAY_OF_YEAR = 3;

Public static int dayOfTheWeek(int day){

return (firstDay + day –1)%7;

}


Result: 0 (Sunday)



I'm a bit lost on how these two problems are connected. I know the key in my teacher's response was:



"This means that all we have left to do it determine what day out of 365 that a given month falls on." If you could help me understand how to solve this problem, you would be helping me tremendously!



I should also add, We are not allowed to use Java's Calendar object to get this working properly!



Here is my current Project:



 import java.util.*;
public class CalendarReformed {
// Here we can change the size of the calendar
public static final int FIRST_DAY_OF_MONTH = 1;
private static final int SIZE = 7;

public static void main(String args){
Scanner console = new Scanner(System.in);
int day = -1;
int month = -1;
String userSelection;
boolean flag = true;

while (flag){

userMenu();
userSelection = console.next();
if (userSelection.equalsIgnoreCase("e")){
System.out.print("Please enter a date:(mm/dd) ");
String date = console.next();
month = monthFromDate(date);
day = dayFromDate(date);
int highlightSelectedDay = day;
displayCalendar(month, highlightSelectedDay);

} else if (userSelection.equalsIgnoreCase("t")){
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DATE);
month = c.get(Calendar.MONTH)+1;
System.out.println("Today's date: " + month +"/"+ day);
displayCalendar(month,day);
} else if (userSelection.equalsIgnoreCase("n")){
if (day != -1 && month != -1){
day = 1;

month = grabNextMonth(month);
displayCalendar(month,day);
} else{
System.out.print("You must have a month selected to go to next month!n");
}
} else if(userSelection.equalsIgnoreCase("p")){
if (day != -1 && month != -1){
day = 1;

month = grabPreviousMonth(month);
displayCalendar(month, day);
} else {
System.out.print("You must first select a month for previous month to function!n");
}
} else if(userSelection.equalsIgnoreCase("q")){
System.out.print("Now exiting the Calendar programn");
System.out.print("Have a nice day!");
flag = false;
} else {
System.out.print(" *USER ERROR DETECTED* n");
System.out.println("Please make a valid selection from the menu!");
}
}

}

// This method will print the month digit and centers it
public static void drawMonth(int month, int daysToSkip, int maxDays){
System.out.println();
int placeMonth = (SIZE * 3)-4;
for (int space = 1; space <= placeMonth; space++){
printSpaces(1);
}
String monthHolder;
if (month == 1){
monthHolder = "*January*";
} else if(month == 2){
monthHolder = "*February*";
}else if (month == 3){
monthHolder = "*March*";
} else if (month == 4){
monthHolder = "*April*";
} else if (month == 5){
monthHolder = "*May*";
} else if (month == 6){
monthHolder = "*June*";
} else if (month == 7){
monthHolder = "*July*";
} else if (month == 8){
monthHolder = "*August*";
} else if (month == 9){
monthHolder = "*September*";
} else if (month == 10){
monthHolder = "*October*";
} else if (month == 11){
monthHolder = "*November*";
} else {
monthHolder = "*December*";
}
System.out.println(monthHolder);

drawArt();

int start = 1;
while (start <= maxDays) {
if (start == 1) {
drawRow(start, maxDays, daysToSkip);
start += 7 - daysToSkip;
} else {
drawRow(start, maxDays, 0);
start += 7;
}
}

// Displays the top of the calendar border
for (int i = 1; i <= SIZE * 7; i++){
System.out.print("_");
}
}

// This method prints one row of our calendar and applies our | dividers
public static void drawRow(int start,int maxDays, int skip){
for (int top = 1; top <= SIZE * 7; top++){
System.out.print("_");
}
System.out.println();

int printDayNum = start;
String dayTool;

System.out.print("|");
int highlightSelectedDay = -1;
for (int i = 1; i <= 7; i++) {
dayTool = "";
if (i > skip && printDayNum <= maxDays) {
if (highlightSelectedDay == printDayNum) {
dayTool += " ->" + printDayNum++ + "*";
} else {
dayTool += printDayNum++;
}
}

while (dayTool.length() < SIZE - 1){
dayTool += " ";
}

dayTool += "|";
System.out.print(dayTool);
}
int height = SIZE /2;
for (int h = 2; h <= height; h++){
System.out.print("n|");
for (int cell = 1; cell <= 7; cell++){
dayTool = "";
while (dayTool.length() < SIZE -1) {
dayTool += " ";
}
dayTool+="|";
System.out.print(dayTool);
}
}
System.out.println();
}


// This method will display month and the day under the calendar
public static void displayDate(int month, int day){
System.out.println();
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}

// This method grabs the month string from the user input and returns it as an integer
public static int monthFromDate( String date){
int index = date.indexOf("/");
String month = date.substring(0,index);
return Integer.parseInt(month);
}


public static void dateError(String prompt){
System.out.print(prompt+"n");
}
// This method grabs the date which is always after the first two spots of the user date String Returns an int
public static int dayFromDate(String date) {
int index = date.indexOf("/");
String day = date.substring(index + 1);
return Integer.parseInt(day);

}
// Handles the ASCII art above calendar
public static void pattern(){
for (int i = 1; i <= 49/6; i++){
System.out.print("\ 0 / ");
}
System.out.println();
for (int i = 1; i <=49/6; i++){
System.out.print("<(.)> ");
}
System.out.println();
for (int i = 1; i <= 49/6; i++){
System.out.print("/ + \ ");
}
System.out.println();
}

public static void displayCalendar(int month, int day) {
int startDay = getStartingDay(month);
int maxDaysInMonth = getMaxDays(month);
drawMonth(month, startDay, maxDaysInMonth);
displayDate(month,day);
}

public static int getStartingDay(int month) {
if (month == 1 || month == 10) {
return (18 + 4) % 7;
} else if (month == 2 || month == 3 || month == 11) {
return ((18 + 4 + 3)) % 7;
} else if (month == 4 || month == 7) {
return ((18 + 4 + 6)) % 7;
} else if (month == 9 || month == 12) {
return ((18 + 4 + 5) % 7);
} else if (month == 5) {
return ((18 + 4 + 1) % 7);
} else {
return ((18 + 4 + 1) % 7);
}

}
public static int getMaxDays(int month){
int numberOfDays;
if (month == 4 || month == 6 || month == 9 || month == 11){
numberOfDays = 30;
} else if (month == 2){
numberOfDays = 29;
} else
numberOfDays = 31;
return numberOfDays;
}

public static int grabNextMonth(int currentMonth) {
if (currentMonth == 12) // if current month is december
{
return 1; // lets give the user January
} else
return currentMonth + 1; // rest of the time just display the next month
}
public static int grabPreviousMonth(int currentMonth){
if (currentMonth == 1){
return 12;
} else
return currentMonth - 1;
}

// A little more art for top of calendar
public static void drawArt(){
System.out.println(" ____ ___ _ ____ ____ ____| ___ ____ ");
System.out.println("| /__ \ | |____| || | /__ \ | \ ");
System.out.println("|____ / \|____|____| ||__ _|/ \| ");
printChars('_',48);
System.out.println();
for (int i = 1; i <= 2; i+=2){
pattern();
}
}

public static void userMenu(){
System.out.println("Please enter a command: ");
System.out.println("tt["e"] to enter a date and display it");
System.out.println("tt["t"] to get today's date and display the corresponding calendar");
System.out.println("tt["n"] to display the next month");
System.out.println("tt["p"] to display the previous month");
System.out.println("tt["q"] to quit the program");
}

// Method that prints desired chars whenever called
public static void printChars(char ch, int num){
for (int i = 1; i <= num; i++){
System.out.print(ch);
}
}

// Method that can printSpaces when called
public static void printSpaces(int num){
for (int i = 1; i <= num; i++){
System.out.print(" ");
}
}

}









share|improve this question















I'm creating a Calendar for my CS class and need to be able to get my calendar months to start on the correct day of the week. My first go at trying to solve this problem looked something like this:



public static int getStartingDay(int month) {

if (month == 1 || month == 10) {

return (18 + 4) % 7;

} else if (month == 2 || month == 3 || month == 11) {

return ((18 + 4 + 3)) % 7;

} else if (month == 4 || month == 7) {

return ((18 + 4 + 6)) % 7;

} else if (month == 9 || month == 12) {

return ((18 + 4 + 5) % 7);

} else if (month == 5) {

return ((18 + 4 + 1) % 7);

} else {

return ((18 + 4 + 1) % 7);

}


I was really happy to see that this was working but when I showed this to my teacher he said it could be done in a much simpler way.



He responded:



"First of all, I want you to recall that I stated we are just concerned with 2018. Therefore, we only need to know what day 2018 started on. From there, we can basically do what we did for the second writing code question on the midterm, where given a day out of 365 for the year, we can determine what day of the week that falls on. This means that all we have left to do it determine what day out of 365 that a given month falls on. This can be done with some addition if we know how many days are in each month. We can just add up all of the previous month's days to get what day our month starts on. "



For the midterm, we were to assume that the year started on Wednesday (3rd day of the week) so my solution looked like this:



Method call : dayOfYear(5); Should return: 0 for Sunday



Public static final int FIRST_DAY_OF_YEAR = 3;

Public static int dayOfTheWeek(int day){

return (firstDay + day –1)%7;

}


Result: 0 (Sunday)



I'm a bit lost on how these two problems are connected. I know the key in my teacher's response was:



"This means that all we have left to do it determine what day out of 365 that a given month falls on." If you could help me understand how to solve this problem, you would be helping me tremendously!



I should also add, We are not allowed to use Java's Calendar object to get this working properly!



Here is my current Project:



 import java.util.*;
public class CalendarReformed {
// Here we can change the size of the calendar
public static final int FIRST_DAY_OF_MONTH = 1;
private static final int SIZE = 7;

public static void main(String args){
Scanner console = new Scanner(System.in);
int day = -1;
int month = -1;
String userSelection;
boolean flag = true;

while (flag){

userMenu();
userSelection = console.next();
if (userSelection.equalsIgnoreCase("e")){
System.out.print("Please enter a date:(mm/dd) ");
String date = console.next();
month = monthFromDate(date);
day = dayFromDate(date);
int highlightSelectedDay = day;
displayCalendar(month, highlightSelectedDay);

} else if (userSelection.equalsIgnoreCase("t")){
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DATE);
month = c.get(Calendar.MONTH)+1;
System.out.println("Today's date: " + month +"/"+ day);
displayCalendar(month,day);
} else if (userSelection.equalsIgnoreCase("n")){
if (day != -1 && month != -1){
day = 1;

month = grabNextMonth(month);
displayCalendar(month,day);
} else{
System.out.print("You must have a month selected to go to next month!n");
}
} else if(userSelection.equalsIgnoreCase("p")){
if (day != -1 && month != -1){
day = 1;

month = grabPreviousMonth(month);
displayCalendar(month, day);
} else {
System.out.print("You must first select a month for previous month to function!n");
}
} else if(userSelection.equalsIgnoreCase("q")){
System.out.print("Now exiting the Calendar programn");
System.out.print("Have a nice day!");
flag = false;
} else {
System.out.print(" *USER ERROR DETECTED* n");
System.out.println("Please make a valid selection from the menu!");
}
}

}

// This method will print the month digit and centers it
public static void drawMonth(int month, int daysToSkip, int maxDays){
System.out.println();
int placeMonth = (SIZE * 3)-4;
for (int space = 1; space <= placeMonth; space++){
printSpaces(1);
}
String monthHolder;
if (month == 1){
monthHolder = "*January*";
} else if(month == 2){
monthHolder = "*February*";
}else if (month == 3){
monthHolder = "*March*";
} else if (month == 4){
monthHolder = "*April*";
} else if (month == 5){
monthHolder = "*May*";
} else if (month == 6){
monthHolder = "*June*";
} else if (month == 7){
monthHolder = "*July*";
} else if (month == 8){
monthHolder = "*August*";
} else if (month == 9){
monthHolder = "*September*";
} else if (month == 10){
monthHolder = "*October*";
} else if (month == 11){
monthHolder = "*November*";
} else {
monthHolder = "*December*";
}
System.out.println(monthHolder);

drawArt();

int start = 1;
while (start <= maxDays) {
if (start == 1) {
drawRow(start, maxDays, daysToSkip);
start += 7 - daysToSkip;
} else {
drawRow(start, maxDays, 0);
start += 7;
}
}

// Displays the top of the calendar border
for (int i = 1; i <= SIZE * 7; i++){
System.out.print("_");
}
}

// This method prints one row of our calendar and applies our | dividers
public static void drawRow(int start,int maxDays, int skip){
for (int top = 1; top <= SIZE * 7; top++){
System.out.print("_");
}
System.out.println();

int printDayNum = start;
String dayTool;

System.out.print("|");
int highlightSelectedDay = -1;
for (int i = 1; i <= 7; i++) {
dayTool = "";
if (i > skip && printDayNum <= maxDays) {
if (highlightSelectedDay == printDayNum) {
dayTool += " ->" + printDayNum++ + "*";
} else {
dayTool += printDayNum++;
}
}

while (dayTool.length() < SIZE - 1){
dayTool += " ";
}

dayTool += "|";
System.out.print(dayTool);
}
int height = SIZE /2;
for (int h = 2; h <= height; h++){
System.out.print("n|");
for (int cell = 1; cell <= 7; cell++){
dayTool = "";
while (dayTool.length() < SIZE -1) {
dayTool += " ";
}
dayTool+="|";
System.out.print(dayTool);
}
}
System.out.println();
}


// This method will display month and the day under the calendar
public static void displayDate(int month, int day){
System.out.println();
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}

// This method grabs the month string from the user input and returns it as an integer
public static int monthFromDate( String date){
int index = date.indexOf("/");
String month = date.substring(0,index);
return Integer.parseInt(month);
}


public static void dateError(String prompt){
System.out.print(prompt+"n");
}
// This method grabs the date which is always after the first two spots of the user date String Returns an int
public static int dayFromDate(String date) {
int index = date.indexOf("/");
String day = date.substring(index + 1);
return Integer.parseInt(day);

}
// Handles the ASCII art above calendar
public static void pattern(){
for (int i = 1; i <= 49/6; i++){
System.out.print("\ 0 / ");
}
System.out.println();
for (int i = 1; i <=49/6; i++){
System.out.print("<(.)> ");
}
System.out.println();
for (int i = 1; i <= 49/6; i++){
System.out.print("/ + \ ");
}
System.out.println();
}

public static void displayCalendar(int month, int day) {
int startDay = getStartingDay(month);
int maxDaysInMonth = getMaxDays(month);
drawMonth(month, startDay, maxDaysInMonth);
displayDate(month,day);
}

public static int getStartingDay(int month) {
if (month == 1 || month == 10) {
return (18 + 4) % 7;
} else if (month == 2 || month == 3 || month == 11) {
return ((18 + 4 + 3)) % 7;
} else if (month == 4 || month == 7) {
return ((18 + 4 + 6)) % 7;
} else if (month == 9 || month == 12) {
return ((18 + 4 + 5) % 7);
} else if (month == 5) {
return ((18 + 4 + 1) % 7);
} else {
return ((18 + 4 + 1) % 7);
}

}
public static int getMaxDays(int month){
int numberOfDays;
if (month == 4 || month == 6 || month == 9 || month == 11){
numberOfDays = 30;
} else if (month == 2){
numberOfDays = 29;
} else
numberOfDays = 31;
return numberOfDays;
}

public static int grabNextMonth(int currentMonth) {
if (currentMonth == 12) // if current month is december
{
return 1; // lets give the user January
} else
return currentMonth + 1; // rest of the time just display the next month
}
public static int grabPreviousMonth(int currentMonth){
if (currentMonth == 1){
return 12;
} else
return currentMonth - 1;
}

// A little more art for top of calendar
public static void drawArt(){
System.out.println(" ____ ___ _ ____ ____ ____| ___ ____ ");
System.out.println("| /__ \ | |____| || | /__ \ | \ ");
System.out.println("|____ / \|____|____| ||__ _|/ \| ");
printChars('_',48);
System.out.println();
for (int i = 1; i <= 2; i+=2){
pattern();
}
}

public static void userMenu(){
System.out.println("Please enter a command: ");
System.out.println("tt["e"] to enter a date and display it");
System.out.println("tt["t"] to get today's date and display the corresponding calendar");
System.out.println("tt["n"] to display the next month");
System.out.println("tt["p"] to display the previous month");
System.out.println("tt["q"] to quit the program");
}

// Method that prints desired chars whenever called
public static void printChars(char ch, int num){
for (int i = 1; i <= num; i++){
System.out.print(ch);
}
}

// Method that can printSpaces when called
public static void printSpaces(int num){
for (int i = 1; i <= num; i++){
System.out.print(" ");
}
}

}






java calendar dayofweek






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 6:36









Ole V.V.

25.6k62549




25.6k62549










asked Nov 10 at 21:07









Nicksc831

12




12












  • Putting aside whether the teacher's approach may be simpler, I am frankly mystified by the magic numbers in your answer. What is the significance of 18? 4? Why do the checks test those specific months? (I'm not actually looking for an answer; I'm encouraging you to think about how you would understand this code if you revisited it a year from now, or if this code were to be handed to someone else to maintain).
    – Andy Turner
    Nov 10 at 21:17












  • Thank you. I have really been struggling with this part of the project and was looking everywhere I could for a solution and wound up using a formula I found to calculate the correct days. I guess I was just so happy to see it working that I didn't think about how it was structured.
    – Nicksc831
    Nov 10 at 21:25










  • Focus on working with concepts you think might be useful rather than finding the "right formula" (or magic numbers). Would numberOfDaysInPreceedingMonths += daysIn2018Months[m]; express a concept that is part of the way you think? Programming is a form of expository writing (but often with the supporting details first if they can be expressed simply ex. int daysIn2018Months = { 31, 28, …}).
    – Tom Blodget
    Nov 11 at 2:38










  • It’s a question with a bit of thought-reading in it, something that very few stackoverflowers excel in. If I’m allowed to try anyway, I would guess that you rteacher means that to find the day of week of March 1, you add the number of days in January and the number of days in February to the first day of the year. Similarly for other months.
    – Ole V.V.
    Nov 11 at 6:33










  • For production code you should never use Calendar, it’s poorly designed and long outdated. Instead for a task like this you would use LocalDate from java.time, the modern Java date and time API. For example LocalDate.of(2018, Month.MARCH, 9).getDayOfWeek().
    – Ole V.V.
    Nov 11 at 6:35




















  • Putting aside whether the teacher's approach may be simpler, I am frankly mystified by the magic numbers in your answer. What is the significance of 18? 4? Why do the checks test those specific months? (I'm not actually looking for an answer; I'm encouraging you to think about how you would understand this code if you revisited it a year from now, or if this code were to be handed to someone else to maintain).
    – Andy Turner
    Nov 10 at 21:17












  • Thank you. I have really been struggling with this part of the project and was looking everywhere I could for a solution and wound up using a formula I found to calculate the correct days. I guess I was just so happy to see it working that I didn't think about how it was structured.
    – Nicksc831
    Nov 10 at 21:25










  • Focus on working with concepts you think might be useful rather than finding the "right formula" (or magic numbers). Would numberOfDaysInPreceedingMonths += daysIn2018Months[m]; express a concept that is part of the way you think? Programming is a form of expository writing (but often with the supporting details first if they can be expressed simply ex. int daysIn2018Months = { 31, 28, …}).
    – Tom Blodget
    Nov 11 at 2:38










  • It’s a question with a bit of thought-reading in it, something that very few stackoverflowers excel in. If I’m allowed to try anyway, I would guess that you rteacher means that to find the day of week of March 1, you add the number of days in January and the number of days in February to the first day of the year. Similarly for other months.
    – Ole V.V.
    Nov 11 at 6:33










  • For production code you should never use Calendar, it’s poorly designed and long outdated. Instead for a task like this you would use LocalDate from java.time, the modern Java date and time API. For example LocalDate.of(2018, Month.MARCH, 9).getDayOfWeek().
    – Ole V.V.
    Nov 11 at 6:35


















Putting aside whether the teacher's approach may be simpler, I am frankly mystified by the magic numbers in your answer. What is the significance of 18? 4? Why do the checks test those specific months? (I'm not actually looking for an answer; I'm encouraging you to think about how you would understand this code if you revisited it a year from now, or if this code were to be handed to someone else to maintain).
– Andy Turner
Nov 10 at 21:17






Putting aside whether the teacher's approach may be simpler, I am frankly mystified by the magic numbers in your answer. What is the significance of 18? 4? Why do the checks test those specific months? (I'm not actually looking for an answer; I'm encouraging you to think about how you would understand this code if you revisited it a year from now, or if this code were to be handed to someone else to maintain).
– Andy Turner
Nov 10 at 21:17














Thank you. I have really been struggling with this part of the project and was looking everywhere I could for a solution and wound up using a formula I found to calculate the correct days. I guess I was just so happy to see it working that I didn't think about how it was structured.
– Nicksc831
Nov 10 at 21:25




Thank you. I have really been struggling with this part of the project and was looking everywhere I could for a solution and wound up using a formula I found to calculate the correct days. I guess I was just so happy to see it working that I didn't think about how it was structured.
– Nicksc831
Nov 10 at 21:25












Focus on working with concepts you think might be useful rather than finding the "right formula" (or magic numbers). Would numberOfDaysInPreceedingMonths += daysIn2018Months[m]; express a concept that is part of the way you think? Programming is a form of expository writing (but often with the supporting details first if they can be expressed simply ex. int daysIn2018Months = { 31, 28, …}).
– Tom Blodget
Nov 11 at 2:38




Focus on working with concepts you think might be useful rather than finding the "right formula" (or magic numbers). Would numberOfDaysInPreceedingMonths += daysIn2018Months[m]; express a concept that is part of the way you think? Programming is a form of expository writing (but often with the supporting details first if they can be expressed simply ex. int daysIn2018Months = { 31, 28, …}).
– Tom Blodget
Nov 11 at 2:38












It’s a question with a bit of thought-reading in it, something that very few stackoverflowers excel in. If I’m allowed to try anyway, I would guess that you rteacher means that to find the day of week of March 1, you add the number of days in January and the number of days in February to the first day of the year. Similarly for other months.
– Ole V.V.
Nov 11 at 6:33




It’s a question with a bit of thought-reading in it, something that very few stackoverflowers excel in. If I’m allowed to try anyway, I would guess that you rteacher means that to find the day of week of March 1, you add the number of days in January and the number of days in February to the first day of the year. Similarly for other months.
– Ole V.V.
Nov 11 at 6:33












For production code you should never use Calendar, it’s poorly designed and long outdated. Instead for a task like this you would use LocalDate from java.time, the modern Java date and time API. For example LocalDate.of(2018, Month.MARCH, 9).getDayOfWeek().
– Ole V.V.
Nov 11 at 6:35






For production code you should never use Calendar, it’s poorly designed and long outdated. Instead for a task like this you would use LocalDate from java.time, the modern Java date and time API. For example LocalDate.of(2018, Month.MARCH, 9).getDayOfWeek().
– Ole V.V.
Nov 11 at 6:35



















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243416%2fhow-can-i-determine-what-day-of-the-week-a-given-month-falls-on-in-java-without%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243416%2fhow-can-i-determine-what-day-of-the-week-a-given-month-falls-on-in-java-without%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

List item for chat from Array inside array React Native

Thiostrepton

Caerphilly