The guidelines for this program follow
Problem B: Year Dates. Objectives: Understanding the Switch structure, helper methods, and using a While loop with a sentinel value.
You are to make a class called Year2012 to manipulate dates when given a month(mm), or a month plus a day(dd) as integer values. It has the following get methods: 1) MonthName which returns a String value that is the name of the Month, e.g. September, June, May, etc. 2) DaysInMonth which returns the number of days in the month. 3)DayOfTheYear which returns the ordinal year date (a number between 1-365, often called the Julian date). Hint, use a for loop to add the days in each prior month, and then add the current month's days. 4) DayOfWeek which returns a String value which is the name of the day, e.g. Monday, Tuesday, etc.
Some of these methods can be used as 'helper' methods for others. All methods will use a switch statement either directly or indirectly. Each method computes a return value from the values sent to it, therefore there are no class attributes, and only a default constructor. All logic must be contained in your own methods. (ie. You will not use existing API classes for your logic.)
Design a tester application that asks the user for a month and day, and then displays the name of the month, the number of days in the month, the day of the week for this date, and the Julian date for this day. Write your program to process dates using a While loop until a sentinel value is entered. Run your program multiple times to test out different days, but turn in a final run using the following five dates: Jan.1, Apr.18, Aug.2, Nov.28, & Dec.15.
I'm having troubles with certain parts of this program. Specifically with the Julian date method and the dayofTheWeek method. Julian date keeps printing out a 1 (I haven't tested many dates), and is a helper method to the dayofTheWeek method, could you take a look at my code and see what my problem is?
public String monthName(int month)
{
String mon = null;
switch (month)
{
case 1:
mon = "January";
break;
case 2:
mon = "February";
break;
case 3:
mon = "March";
break;
case 4:
mon = "April";
break;
case 5:
mon = "May";
break;
case 6:
mon = "June";
break;
case 7:
mon = "July";
break;
case 8:
mon = "August";
break;
case 9:
mon = "September";
break;
case 10:
mon = "October";
break;
case 11:
mon = "November";
break;
case 12:
mon = "December";
break;
default:
mon = "Inccorect entry";
break;
}
return mon;
}
public int daysInMonth(int month)
{
int days = 0;
switch (month)
{
case 1:
days = 31;
break;
case 2:
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
days = 0;
}
return days;
}
public int dayOfTheYear(int month, int day)
{
int julian = 0;
for (int count = 1; count == month; count++)
{
julian += daysInMonth(count);
}
return julian;
}
public String dayOfWeek(int month, int day)
{
int daysSoFar = dayOfTheYear(month, day);
int weekDay = daysSoFar % 7;
String dayName = null;
switch (weekDay)
{
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Incorrect entry";
}
return dayName;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Year2012 year = new Year2012();
System.out.println("Please enter a month using integers (Jan = 1): ");
int month = keyboard.nextInt();
System.out.println("Please enter a day within that month: ");
int day = keyboard.nextInt();
System.out.println("Month: " + year.monthName(month));
System.out.println("Number of days in month: " + year.daysInMonth(month));
System.out.println("Day of the week: " + year.dayOfWeek(month, day));
System.out.println("Julian date: " + year.dayOfTheYear(month, day));
}
}
You got it wrong in the for loop setting the julian value. Try this:
int julian = 0;
for (int count = 1; count < month; count++)
{
julian += daysInMonth(count);
}
return julian + day;
This loop uses count < month instead of count == month. It also returns julian + day.
You have a couple issues in the julian value calculation. Try this:
public int dayOfTheYear(int month, int day)
{
int julian = 0;
for (int count = 1; count < month; count++) //note this loop will not run for Jan(as the logic below will cover that
{
julian += daysInMonth(count);
}
julian += day;
return julian;
}
This loop uses count < month instead of count == month, and then adds the days from the input before returning the answer.
note this loop will not run for Jan as in that case you just want to add the days entered.
Your for loop condition is count == month.
public int dayOfTheYear(int month, int day)
{
int julian = 0;
for (int count = 1; count == month; count++)
{
julian += daysInMonth(count);
}
return julian;
}
This means the loop body will only execute when the month input is 1, and then only once. Did you mean count < month?
Related
import java.util.Scanner;
public class DaysInMonth
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:")
int year = input.nextInt(); enter code here
System.out.print("Enter a month:");
int month = input.nextInt(); enter code here
int days = 0;
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);
switch (month){
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " +days+ " Days in Month "+month+ " of Year " +year+ ".\n";
System.out.println(response); // new line to show the result to the screen.
}
}
Why can't I type in January to get the same output result if I type 1? It should print "There are 31 days in the month of January of Year 2018" I initialized the month so it should read January or any other month.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
You can use Strings in a switch statement to check for several equivalent cases:
switch (monthInput.toLowerCase()) {
case "january":
case "jan":
case "1":
days = 31;
break;
case "february":
case "feb":
case "2":
days = isLeapYear ? 29 : 28;
break;
case "march":
case "mar":
case "3":
days = 31;
break;
// etc.
default:
System.out.println(monthInput + " is not a valid month");
input.close();
System.exit(0);
}
But this means you have to read your input as a String, not as an int...
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); // enter code here
input.nextLine(); // read the rest of the line (if any)
System.out.print("Enter a month:");
String monthInput = input.nextLine();
Note the use of input.nextLine(); after the .nextInt() — this is because the nextInt() call does not consume all of the input, it only reads the int that you typed for the Year, it does not read the newline (enter key), so you have to read that to be ready to read the next input, which is the month number or name.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
A simple approach is to use name array
// before main.
static final String[] MONTH = "?,Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
// inside main
String monthStr = MONTH[month];
Add the full month names as needed.
I need to know which day and day name is on a specific date. And somehow I made a mistake because for years with 19.. it works but at 2000 I can't get the right day anymore. For example if I use the date 9.1.2001 it doesn't say me the day, instead the error of the switch I made occurs.
and i shouldn't use the calendar methods
here is my code:
public class FindDay {
public static void main(String[] args) {
System.out.println("Type a day: ");
int day = In.readInt();
System.out.println("Type a month: ");
int month = In.readInt();
System.out.println("Type a year: ");
int year = In.readInt();
if(day < 1 || day > 32) {
System.out.println("Type valid day");
}else if (month < 1 || month >12) {
System.out.println("Type valid month");
}else if (year < 1900) {
System.out.println("Type valid year");
}
int wholeDaysYear; //to calculate how much days a year has
if (year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0) ) {
wholeDaysYear = 366;
}else {
wholeDaysYear = 365;
}
int monthDays = 0; //calculates days to this month
int february; //if February has 28 or 2 days
if(wholeDaysYear ==366) {
february = 29;
}else {
february = 28;
}
switch(month) {
case 1: monthDays= 0; break;
case 2: monthDays =31; break;
case 3: monthDays= 31+february; break;
case 4: monthDays= 31+february+31; break;
case 5: monthDays= 31+february+31+30; break;
case 6: monthDays= 31+february+31+30+31; break;
case 7: monthDays= 31+february+31+30+31+30; break;
case 8: monthDays= 31+february+31+30+31+30+31; break;
case 9: monthDays= 31+february+31+30+31+30+31+31; break;
case 10: monthDays= 31+february+31+30+31+30+31+31+30; break;
case 11: monthDays= 31+february+31+30+31+30+31+31+30+31; break;
case 12: monthDays= 31+february+31+30+31+30+31+31+30+31+30; break;
default: System.out.println("Enter valid month!");break;
}
int leapYear = ((year-1) / 4 - 474) - ((year-1) / 100 - 18) + ((year-1) / 400 - 4); //calculates the leap years
int allDays =(((year - leapYear)-1900)*wholeDaysYear)+monthDays+day-1; //Calculates all days
System.out.println(allDays);
int dayName = allDays % 7;
String dayNames = null; //gives the days their name
switch (dayName) {
case 1: dayNames = "Monday";break;
case 2: dayNames = "Tuesday";break;
case 3: dayNames = "Wendesday";break;
case 4: dayNames = "Thursday";break;
case 5: dayNames = "Friday";break;
case 6: dayNames = "Saturday";break;
case 7: dayNames = "Sunday";break;
default: System.out.println("Type valid Input");break;
}
System.out.println(dayNames);
}
}
You don't have to work so hard... assuming you have the day of the month, month of the year and full-year, you can simply do (example):
LocalDate ld = LocalDate.of(1999, 12, 12);
System.out.println(ld.getDayOfWeek()); // prints SUNDAY
LocalDate is available since Java 8.
As for your code, two bugs that are easy to spot are:
The cases in the switch go from 1 to 7 while they should go from 0 to 6 since you're calculating the reminder out of 7.
int dayName = allDays % 7; here you assume that the first day of the year is Monday (according to your case switch) which is not necessarily true.
You can try something like this:
Date yourDate;
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //or Calendar.DAY_OF_WEEK
// etc.
I'm writing a program that takes in the users birth information, year, month, day, hour, minute. The program is the following:
Use the getRangedInt method to input the year (1965-2000), month
(1-12), Day*, hours (1 – 24), Minutes (1-59) of a person’s birth.
Note: use a switch() conditional selector structure to limit the user
to the correct number of days for the month they were born in. For
instance if they were born in Feb [1-29], Oct [1-31]. HINT: there are
only a few groups here not 12 different ones!
I'm absolutely confused with the day part. I have managed to get everything else to work except understand what I'm supposed to do for the day.
My code:
public static void main(String[] args)
{
int year, month, day, hour, minutes;
String msg="";
boolean done = true;
Scanner in = new Scanner(System.in);
while(done)
{
year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);
month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", day, day);
hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);
System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
}
}
The getIntInRange just does a basic input to get the number in range.
I'm confused because I don't know how to do the range for the day since there is also supposed to be a switch used.
This is a very strange requirement.
It looks like what is requested from you looks like something like this:
int numberOfDays;
switch (month) {
case 1: // $FALL-THROUGH
case 3: // $FALL-THROUGH
case 5: // $FALL-THROUGH
case 7: // $FALL-THROUGH
case 9: // $FALL-THROUGH
case 11:
numberOfDays = 31;
break;
case 4: // $FALL-THROUGH
case 6: // $FALL-THROUGH
case 8: // $FALL-THROUGH
case 10: // $FALL-THROUGH
case 12:
numberOfDays = 30;
break;
case 2:
numberOfDays = (0 == year / 4) ? 29 : 28;
break;
default:
throw new IllegalArgumentException("month not 1-12");
} // switch (too long for my liking)
and then
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, numberOfDays);
This utilizes a fall-through construct available in switches, so if you meet a condition, you are going to execute until a return statement (or break/throw).
Please remember that the alternative is to have something like:
private static final Set<Integer> MONTHS_30_DAYS = Sets.newTreeSet(4, 6, 8, 10, 12);
private static final Set<Integer> MONTHS_31_DAYS = Sets.newTreeSet(1, 3, 5, 7, 9, 11);
public static int numberOfDays(int month, int year) {
if (MONTHS_30_DAYS.contains(month)) {
return 30;
} else if (MONTHS_31_DAYS.contains(month)) {
return 31;
} else {
return (0 == year / 4) ? 29 : 28;
}
}
Here your day is dependent on the month entered. So firstly you'd want to take the month entered by the user as an Integer like you're doing now and proceed to use that number in a switch:
int month = 0;
int numberOfDays;
switch (month) {
case 1: numberOfDays = DaysInJanuary;
break;
case 2: numberOfDays = DaysInFebruary;
break;
case 3: numberOfDays = DaysInMarch;
break;
case 4: numberOfDays = DaysInApril;
break;
case 5: numberOfDays = DaysInMay;
break;
case 6: numberOfDays = DaysInJune;
break;
case 7: numberOfDays = DaysInJuly;
break;
case 8: numberOfDays = DaysInAugust;
break;
case 9: numberOfDays = DaysInSeptember;
break;
case 10: numberOfDays = DaysInOctober;
break;
case 11: numberOfDays = DaysInNovember;
break;
case 12: numberOfDays = DaysInDecember;
break;
default: throw new IllegalArgumentException("Not a valid month");
break;
}
You can then proceed to set your variable for the max day range.
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, numberOfDays);
Hope this helped.
Your day range depends on the previous month number the user entered, so you have to check that in order to know which day range to display. What the hint tells you is that you don't need a different range of valid days for each month because some months share the same range. Here are the number of days in a month:
January 31
February 28/29
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
As you can see, there are only 3 groups and the assignment wants you to utilize fallthrough - when you don't break in a switch:
int upperDaysLimit;
switch(month) {
case 1:
case 3:
case 5:
//...
case 12: upperDaysLimit = 31;
break;
case 4:
case 6:
// and so on
}
and now you can use that range limit on your days inquiry:
day = SafeInput.getIntInRange(in, "Enter the day you were born: ", 1, upperDaysLimit);
If you're required to use switch statement, you can split months by the number of days in them. There will be 3 groups. Than you can use a switch statement as follows:
switch (month) {
case 1:
case 3:
case 5:
return 31;
case 2: {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
return 29;
else
return 28;
}
case 4:
case 6:
return 30;
default:
throw new IllegalArgumentException("some error text");
}
The switch statement in the example is not full, you should write a case statements for every month. Basically you're returning the upper value for day.
How to know how many days has particular month of particular year?
String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this
Java 8 and later
#Warren M. Nocos.
If you are trying to use Java 8's new Date and Time API, you can use java.time.YearMonth class. See Oracle Tutorial.
// Get the number of days in that month
YearMonth yearMonthObject = YearMonth.of(1999, 2);
int daysInMonth = yearMonthObject.lengthOfMonth(); //28
Test: try a month in a leap year:
yearMonthObject = YearMonth.of(2000, 2);
daysInMonth = yearMonthObject.lengthOfMonth(); //29
Java 7 and earlier
Create a calendar, set year and month and use getActualMaximum
int iYear = 1999;
int iMonth = Calendar.FEBRUARY; // 1 (months begin with 0)
int iDay = 1;
// Create a calendar object and set year and month
Calendar mycal = new GregorianCalendar(iYear, iMonth, iDay);
// Get the number of days in that month
int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28
Test: try a month in a leap year:
mycal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
daysInMonth= mycal.getActualMaximum(Calendar.DAY_OF_MONTH); // 29
Code for java.util.Calendar
If you have to use java.util.Calendar, I suspect you want:
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Code for Joda Time
Personally, however, I'd suggest using Joda Time instead of java.util.{Calendar, Date} to start with, in which case you could use:
int days = chronology.dayOfMonth().getMaximumValue(date);
Note that rather than parsing the string values individually, it would be better to get whichever date/time API you're using to parse it. In java.util.* you might use SimpleDateFormat; in Joda Time you'd use a DateTimeFormatter.
You can use Calendar.getActualMaximum method:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);
java.time.LocalDate
From Java 1.8, you can use the method lengthOfMonth on java.time.LocalDate:
LocalDate date = LocalDate.of(2010, 1, 19);
int days = date.lengthOfMonth();
This is the mathematical way:
For year (e.g. 2012), month (1 to 12):
int daysInMonth = month !== 2 ?
31 - (((month - 1) % 7) % 2) :
28 + (year % 4 == 0 ? 1 : 0) - (year % 100 == 0 ? 1 : 0) + (year % 400 == 0 ? 1 : 0)
if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
} else if (month == 2) {
daysInMonth = (leapYear) ? 29 : 28;
else {
daysInMonth = 31;
}
I would go for a solution like this:
int monthNr = getMonth();
final Month monthEnum = Month.of(monthNr);
int daysInMonth;
if (monthNr == 2) {
int year = getYear();
final boolean leapYear = IsoChronology.INSTANCE.isLeapYear(year);
daysInMonth = monthEnum.length(leapYear);
} else {
daysInMonth = monthEnum.maxLength();
}
If the month isn't February (92% of the cases), it depends on the month only and it is more efficient not to involve the year. This way, you don't have to call logic to know whether it is a leap year and you don't need to get the year in 92% of the cases.
And it is still clean and very readable code.
Simple as that,no need to import anything
public static int getMonthDays(int month, int year) {
int daysInMonth ;
if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
}
else {
if (month == 2) {
daysInMonth = (year % 4 == 0) ? 29 : 28;
} else {
daysInMonth = 31;
}
}
return daysInMonth;
}
In Java8 you can use get ValueRange from a field of a date.
LocalDateTime dateTime = LocalDateTime.now();
ChronoField chronoField = ChronoField.MONTH_OF_YEAR;
long max = dateTime.range(chronoField).getMaximum();
This allows you to parameterize on the field.
Lets make it as simple if you don't want to hardcode the value of year and month and you want to take the value from current date and time:
Date d = new Date();
String myDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
int iDayFromDate = Integer.parseInt(myDate.substring(0, 2));
int iMonthFromDate = Integer.parseInt(myDate.substring(3, 5));
int iYearfromDate = Integer.parseInt(myDate.substring(6, 10));
YearMonth CurrentYear = YearMonth.of(iYearfromDate, iMonthFromDate);
int lengthOfCurrentMonth = CurrentYear.lengthOfMonth();
System.out.println("Total number of days in current month is " + lengthOfCurrentMonth );
// 1 means Sunday ,2 means Monday .... 7 means Saturday
//month starts with 0 (January)
MonthDisplayHelper monthDisplayHelper = new MonthDisplayHelper(2019,4);
int numbeOfDaysInMonth = monthDisplayHelper.getNumberOfDaysInMonth();
Following method will provide you the no of days in a particular month
public static int getNoOfDaysInAMonth(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal.getActualMaximum(Calendar.DATE));
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*
* 44. Return the number of days in a month
* , where month and year are given as input.
*/
public class ex44 {
public static void dateReturn(int m,int y)
{
int m1=m;
int y1=y;
String str=" "+ m1+"-"+y1;
System.out.println(str);
SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");
try {
Date d=sd.parse(str);
System.out.println(d);
Calendar c=Calendar.getInstance();
c.setTime(d);
System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
dateReturn(2,2012);
}
}
public class Main {
private static LocalDate local=LocalDate.now();
public static void main(String[] args) {
int month=local.lengthOfMonth();
System.out.println(month);
}
}
The use of outdated Calendar API should be avoided.
In Java8 or higher version, this can be done with YearMonth.
Example code:
int year = 2011;
int month = 2;
YearMonth yearMonth = YearMonth.of(year, month);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth);
You can use Calendar.getActualMaximum method:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
int numDays = calendar.getActualMaximum(Calendar.DATE);
And month-1 is Because of month takes its original number of month while in method takes argument as below in Calendar.class
public int getActualMaximum(int field) {
throw new RuntimeException("Stub!");
}
And the (int field) is like as below.
public static final int JANUARY = 0;
public static final int NOVEMBER = 10;
public static final int DECEMBER = 11;
An optimal and performant variance:
public static int daysInMonth(int month, int year) {
if (month != 2) {
return 31 - (month - 1) % 7 % 2;
}
else {
if ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0)) { // leap year
return 29;
} else {
return 28;
}
}
}
For more details on the leap algorithm check here
Number of days in particular year - Java 8+ solution
Year.now().length()
An alternative solution is to use a Calendar object. Get the current date and set the day so it is the first of the month. Then add one month and take away one day to get the last day of the current month. Finally fetch the day to get the number of days in the month.
Calendar today = getInstance(TimeZone.getTimeZone("UTC"));
Calendar currMonthLastDay = getInstance(TimeZone.getTimeZone("UTC"));
currMonthLastDay.clear();
currMonthLastDay.set(YEAR, today.get(YEAR));
currMonthLastDay.set(MONTH, today.get(MONTH));
currMonthLastDay.set(DAY_OF_MONTH, 1);
currMonthLastDay.add(MONTH, 1);
currMonthLastDay.add(DAY_OF_MONTH, -1);
Integer daysInMonth = currMonthLastDay.get(DAY_OF_MONTH);
String MonthOfName = "";
int number_Of_DaysInMonth = 0;
//year,month
numberOfMonth(2018,11); // calling this method to assign values to the variables MonthOfName and number_Of_DaysInMonth
System.out.print("Number Of Days: "+number_Of_DaysInMonth+" name of the month: "+ MonthOfName );
public void numberOfMonth(int year, int month) {
switch (month) {
case 1:
MonthOfName = "January";
number_Of_DaysInMonth = 31;
break;
case 2:
MonthOfName = "February";
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
MonthOfName = "March";
number_Of_DaysInMonth = 31;
break;
case 4:
MonthOfName = "April";
number_Of_DaysInMonth = 30;
break;
case 5:
MonthOfName = "May";
number_Of_DaysInMonth = 31;
break;
case 6:
MonthOfName = "June";
number_Of_DaysInMonth = 30;
break;
case 7:
MonthOfName = "July";
number_Of_DaysInMonth = 31;
break;
case 8:
MonthOfName = "August";
number_Of_DaysInMonth = 31;
break;
case 9:
MonthOfName = "September";
number_Of_DaysInMonth = 30;
break;
case 10:
MonthOfName = "October";
number_Of_DaysInMonth = 31;
break;
case 11:
MonthOfName = "November";
number_Of_DaysInMonth = 30;
break;
case 12:
MonthOfName = "December";
number_Of_DaysInMonth = 31;
}
}
This worked fine for me.
This is a Sample Output
import java.util.*;
public class DaysInMonth {
public static void main(String args []) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); //Moved here to get input after the question is asked
System.out.print("Enter a month:");
int month = input.nextInt(); //Moved here to get input after the question is asked
int days = 0; //changed so that it just initializes the variable to zero
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
switch (month) {
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " + days + " Days in Month " + month + " of Year " + year + ".\n";
System.out.println(response); // new line to show the result to the screen.
}
} //abhinavsthakur00#gmail.com
String date = "11-02-2000";
String[] input = date.split("-");
int day = Integer.valueOf(input[0]);
int month = Integer.valueOf(input[1]);
int year = Integer.valueOf(input[2]);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.DATE, day);
//since month number starts from 0 (i.e jan 0, feb 1),
//we are subtracting original month by 1
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);
I have a project due soon. We have to write a program that asks for a year and prints out a calendar. We can only use one while, one for, and one switch loop. (and no arrays! ugh) Im having trouble figuring out how to print out the days of each month, starting with the first day of the first week, as most months will not start on Sunday.
import java.util.*;
import java.util.Calendar;
class Lab2 {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
System.out.print("What year do you want to view? ");
int year = user.nextInt();
System.out.printf("%12d\n", year);
System.out.println();
boolean leap = isLeap(year);
int firstDay = JulianDate(year);
monthLoop(year, firstDay, leap);
}
public static boolean isLeap(int year) {
boolean verdict = false;
if (year % 100 == 0 && year % 400 == 0) {
verdict = true;
}
if(year % 100 != 0 && year % 4 == 0) {
verdict = true;
}
return verdict;
}
public static int JulianDate(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, 1);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return dayOfWeek;
}
public static void monthLoop(int year, int firstDay, boolean leap) {
for(int i=1; i <= 12; i++) {
switch (i) {
case 1: System.out.printf("%13s\n", "January");
break;
case 2: System.out.printf("%13s\n", "February");
break;
case 3: System.out.printf("%12s\n", "March");
break;
case 4: System.out.printf("%12s\n", "April");
break;
case 5: System.out.printf("%11s\n", "May");
break;
case 6: System.out.printf("%11s\n", "June");
break;
case 7: System.out.printf("%11s\n", "July");
break;
case 8: System.out.printf("%13s\n", "August");
break;
case 9: System.out.printf("%14s\n", "September");
break;
case 10: System.out.printf("%13s\n", "October");
break;
case 11: System.out.printf("%14s\n", "November");
break;
case 12: System.out.printf("%14s\n", "December");
break;
}
System.out.println("S M Tu W Th F S");
}
}
}
You would get the day of the week, as in this post, of the first day of the month and then start the counter from there.
How to get the day of the week in Java
For instance, if the day of the week was 5, you would put 4 "blanks" before the first date. The trick is that when you are doing your mod, to determine if there should be a new line, it would be
(dayofMonth + firstDayOfWeekOfMonth) % 7