How to reset int values - java

Trying to write a code for my intro to java course but unable to reset int value.
For my intro course, I have to write a program that determines a due date based on the type of book the user is checking out. I am not allowed to use any date formats, just simply inputting month day and year as integers.
The main part of this program is that new books have a 14 day check out and non -new books have a 21 day check out limit. I have figured out how to add the specified number of days based on the type of book, but given that days, months and year are defined as integers, how would I reset the days if the inputted date of the check out exceeds the number of day within that particular month?
I know how to format it to display it continuing over to the next month. But say the user inputs the check out day is the 15 of February, how would my program know how to restart counting on the next month but also know when it's reaching its limit of either 14 or 21 days?
String releaseType;
int coMonth, coYear;
int coDays = 0;
// determing how many days added to due date
if (releaseType == "NEW"){
coDays += 14;
}else{
coDays += 21;
}
if (coDays > 30){
coMonth +=1;
}
if (coMonth >12){
coYear +=1;
}
System.out.println("You due date is " + coMonth + "/" + coDays + "/" + coYear);
Input data: NEW, 2 (month) 15 (day) 2019 (year)
output: You due date is 3/36/2019

Below is the outline for a class that should do what you want.
class Date
{
Date(int InputDay, int InputMonth, int InputYear;
{
Day = InputDay;
Month = InputMonth;
Year = InputYear;
}
public final int GetDay()
{
return Day;
}
public final int GetMonth()
{
return Month;
}
public final int GetYear()
{
return Year;
}
// Increments the current date by NumDays.
public final Date AddDays(int NumDays)
{
int TempDay = Day;
int TempMonth = Month;
int TempYear = Year;
while (NumDays > 0)
{
switch (Month)
{
case 1: // Jan
{
TempDay += NumDays;
if (TempDay > 31)
{
NumDays = TempDay - 31;
TempDay = 1;
TempMonth++;
}
else
{
NumDays = 0;
}
} break;
case 2: // Feb
{
TempDay += NumDays;
if (TempDay > 28 && IsLeapYear() == false)
{
NumDays = TempDay - 28;
TempDay = 1;
TempMonth++;
}
else if (TempDay > 29 && IsLeapYear() == true)
{
NumDays = TempDay - 29;
TempDay = 1;
TempMonth++;
}
else
{
NumDays = 0;
}
} break;
// Fill in the rest of the months. I've done the
// important ones.
case 12: // Dec
{
TempDay += NumDays;
if (TempDay > 31)
{
NumDays = TempDay - 31;
TempDay = 1;
TempMonth = 1;
TempYear++;
}
else
{
NumDays = 0;
}
} break;
} // End switch
} // End while loop
return new Date(TempDay, TempMonth, TempYear);
}
private boolean IsLeapYear()
{
boolean LeapYear = false;
// Note: In the Gregorian calendar, it is also a leap year if the
// year is divisible by 400 but it's not a leap year if it is
// divisible by 100.
if ( (Year % 4 == 0 && Year % 100 != 0) || Year % 400 == 0)
{
LeapYear = true;
}
return LeapYear;
}
private final int Day;
private final int Month; // Range: 1 - 12
private final int Year;
}
It would be used as follows:
Date Today = new Date(7,10,2019), DueDate;
DueDate = Today.AddDays(21);

Related

"How to fix 'class, interface, or enum expected' for my code

I am unable to find the solution for my code, I receive a 'class, interface, or enum expected' when trying to compile my code.
I have tried to research on how to fox the problem but I was unfortunately unable to do so as it seems like nothing is working for me...also if there are any errors that would lead up to it not working once this part is fixed, please let me know as to what I can change!
The code:
class MyDate {
//properties of date object
private int day, month, year;
//Constructor with arguments
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public boolean isValidDate() {
if (month > 12 || month < 1 || day < 1) { // if negative values found
return false;
} else if (year <= 1582 && month <= 10 && day <= 15) { // starting date
// checking
return false;
} // for 31 day months
else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day > 31) {
return false;
}
} // for 30 day months
else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
return false;
}
} else if (month == 2) // February check
{
if (isLeapYear()) // Leap year check for February
{
if (day > 29) {
return false;
}
} else {
if (day > 28) {
return false;
}
}
}
return true;
}
// checks if this year is leap year
private boolean isLeapYear() {
if (year % 4 != 0) {
return false;
} else if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else {
return true;
}
}
/**
* #return the day
*/
public int getDay() {
return day;
}
/**
* #param day
* the day to set
*/
public void setDay(int day) {
this.day = day;
}
/**
* #return the month
*/
public int getMonth() {
return month;
}
/**
* #param month
* the month to set
*/
public void setMonth(int month) {
this.month = month;
}
/**
* #return the year
*/
public int getYear() {
return year;
}
/**
* #param year
* the year to set
*/
public void setYear(int year) {
this.year = year;
}
#Override
public String toString() {
return day + "/" + month + "/" + year;
}
}
import java.util.Scanner;
public class MyCalendar {
//enums for days of week
public static enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
};
//enum for month of year
public static enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,
OCTOBER, NOVEMBER, DECEMBER;
};
//enums for week numbers
public static enum Week { FIRST, SECOND, THIRD, FOURTH;
};
//to store Date object
private MyDate date;
//constructor taking mydate object
public MyCalendar(MyDate enteredDate) {
this.date = enteredDate;
}
//main method
public static void main(String[] args) {
boolean validDate = false; //valid date false
Scanner input = new Scanner(System.in); //scanner for input
MyDate enteredDate = null;
//till valid date found
while (!validDate) {
System.out.print("Enter the date as day month year : ");
//taking input and creating date object
enteredDate = new MyDate(input.nextInt(), input.nextInt(),
input.nextInt());
//validdating date object
if (enteredDate.isValidDate()) { //if valid
MyCalendar myCalendar = new MyCalendar(enteredDate); //creating
calendar object
myCalendar.printDateInfo(); //printing date info
myCalendar.printCalendar(); //printing calendar
validDate = true; //setting validate to true
} else {
System.out.println("Please enter a Valid Date...");
}
}
input.close();
}
// returns number of days in current month
private int getNumberOfDays() {
int days = 31;
int month = date.getMonth();
if (month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
return days;
}
//print calendar of this month
public void printCalender() {
System.out.println("\n\nThe Calendar of "+Month.values()
[date.getMonth()-1]+" "+date.getYear()+" is :");
int numberOfMonthDays = getNumberOfDays();
Day firstWeekdayOfMonth = getDayOfWeek(1, date.getMonth(),
date.getYear());
int weekdayIndex = 0;
System.out.println("SUN MON TUE WED THU FRI SAT"); // The order of days
// depends on your
// calendar
for (int day = 0; Day.values()[day] != firstWeekdayOfMonth; day++) {
System.out.print(" "); // this loop to print the first day in
his
// correct place
weekdayIndex++;
}
for (int day = 1; day <= numberOfMonthDays; day++) {
if (day < 10)
System.out.print(day + " ");
else
System.out.print(day);
weekdayIndex++;
if (weekdayIndex == 7) {
weekdayIndex = 0;
System.out.println();
} else {
System.out.print(" ");
}
}
System.out.println();
}
//method to print about date information in literal form
public void printDateInfo() {
System.out.println(date + " is a " + getDayOfWeek(date.getDay(),
date.getMonth(), date.getYear())
+ " located in the " + Week.values()[getWeekOfMonth() - 1] + "
week of "
+ Month.values()[date.getMonth() - 1] + " " + date.getYear());
}
/*
* gets day of the week, returns enum type Day
*
* day of week (h) = (q+(13*(m+1)/5)+K+(K/4)+(J/4)+5J)%7 ,q- day of month,
* m- month, k = year of century (year%100), J = (year/100)
*/
public Day getDayOfWeek(int day, int month, int year) {
int q = day;
int m = month;
if (m < 3) {
m = 12 + date.getMonth();
year = year - 1;
}
int K = year % 100;
int J = year / 100;
//calculating h value
int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;
Day output = null;
if (h < Day.values().length && h >= 0) {
output = Day.values()[h - 1]; //getting respective enum value
}
return output; //returning enum value
}
// get week number of current date
public int getWeekOfMonth() {
int days = date.getDay();
int weeks = days / 7;
days = days % 7;
if (days > 0)
weeks++;
return weeks;
}
}
The error:
MyCalendar.java:120: class, interface, or enum expected
import java.util.Scanner;
^
Error given when I move the import to the top (UPDATED):
MyCalendar.java:164: cannot find symbol
symbol : method printCalendar()
location: class MyCalendar
myCalendar.printCalendar(); //printing calendar
Expected code:
java MyCalendar 29/02/2019
29/02/2019 in not a valid date, please re-input a valid date: 25/05/2019
25/05/2019 is a Saturday and located in the fourth week of May 2019
The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
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
the method public void printCalender() should be called or invoked as printCalender() not as printCalendar()
your method is printCalender() whereas you are calling printCalendar() which does not exist.

How to calculate no of days in a month? User to enter the no of the month [duplicate]

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);

How I can match jalili calender with hijri calendar

I want to show jalali calendar and hijri calendar at the same time, but i don't know how to match jalali days with hijri days. I searched and found the source code below. It shows jalali calendar but I don't know how to match two calendars. Hijri calendar does'nt have any specific pattern for months.
import javax.swing.JOptionPane;
public class TestCal {
/** Main method */
public static void main(String[] args) {
// Prompt the user to enter year
String yearString = JOptionPane.showInputDialog(
"Lotfan Sale morede nazar ra vared konid (Masalan 1390):");
// Convert string into integer
int year = Integer.parseInt(yearString);
// Prompt the user to enter month
String monthString = JOptionPane.showInputDialog(
"Lotfan mahe khod ra niz az miane adade 1 ta 12 bargozinid:");
// Convert string into integer
int month = Integer.parseInt(monthString);
// Print calendar for the month of the year
printMonth(year, month);
}
/** Print the calendar for a month in a year */
static void printMonth(int year, int month) {
// Print the headings of the calendar
printMonthTitle(year, month);
// Print the body of the calendar
printMonthBody(year, month);
}
/** Print the month title, e.g., May, 1999 */
static void printMonthTitle(int year, int month) {
System.out.println(" " + getMonthName(month)
+ " " + year);
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
/** Get the English name for the month */
public static String getMonthName(int month) {
String monthName = null;
switch (month) {
case 1: monthName = "Farvardin"; break;
case 2: monthName = "Ordibehesht"; break;
case 3: monthName = "Khordad"; break;
case 4: monthName = "Tir"; break;
case 5: monthName = "Mordad"; break;
case 6: monthName = "Shahrivar"; break;
case 7: monthName = "Mehr"; break;
case 8: monthName = "Aban"; break;
case 9: monthName = "Azar"; break;
case 10: monthName = "Dey"; break;
case 11: monthName = "Bahman"; break;
case 12: monthName = "Esfand";
}
return monthName;
}
/** Print month body */
public static void printMonthBody(int year, int month) {
// Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);
// Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);
// Pad space before the first day of the month
int i = 0;
for (i = 0; i < startDay; i++)
System.out.print(" ");
for (i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10)
System.out.print(" " + i);
else
System.out.print(" " + i);
if ((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}
/** Get the start day of the first day in a month */
public static int getStartDay(int year, int month) {
// Get total number of days since 1/1/1800
int startDay1300 = 1;
int totalNumberOfDays = getTotalNumberOfDays(year, month);
// Return the start day
return (totalNumberOfDays + startDay1300) % 7;
}
/** Get the total number of days since Jan 1, 1800 */
static int getTotalNumberOfDays(int year, int month) {
int total = 0;
// Get the total days from 1800 to year - 1
for (int i = 1300; i < year; i++)
if (isLeapYear(i))
total = total + 366;
else
total = total + 365;
// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumberOfDaysInMonth(year, i);
return total;
}
/** Get the number of days in a month */
public static int getNumberOfDaysInMonth(int year, int month) {
if (month <= 6 && month > 0)
return 31;
else if (month < 12 && month > 6)
return 30;
if (month == 12) return isLeapYear(year) ? 30 : 29;
return 0; // If month is incorrect
}
/** Determine if it is a leap year */
public static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 3 && year % 100 != 0);
}
}
A very simple approach:
Take a common epoch between two calendars
Develop/Find algorithms to convert calendar date to/from number of days between that epoch.
Convert date from calendar type A to epoch-delta and epoch-delta to calendar type B.
I have implemented a simple C library to convert between dates in various calendars. The code is available here. You can extract algorithms and implement them in your own language of choice. In case you are using C/C++, you can simply:
#include <calendars/cl-calendar.h>
int16_t year;
uint8_t month;
uint16_t day;
convert_date(CAL_ISLAMIC_CIVIL, CAL_SOLAR_HIJRI,
1396, 7, 11, &year, &month, &day);
printf("1396/07/11 AP is: %d/%d/%d Hijri", year, month, day);
which will print:
$ 1396/07/11 AP is: 1439/1/12 Hijri
Notes:
Jalali calendar is not being used anymore. You probably want to use Solar Hijri Calendar.
Hijri Calendar is not tabular. You probably mean Islamic Civil Clanndar

How to avoid return null on my case?

I need to write a Java program (class Date) and "class NextDay that calculates and prints the date of the next day by entering the day, month, and year."
At public Date getNextDay() method I must use return null, otherwise it gives error. How can I avoid return null?
Here are my codes;
public class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
public int getMaxDaysInMonth()
{
int daysInMonth = 0;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 2:
if(isLeapYear())
{
daysInMonth = 29;
}
else
{
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
}
return daysInMonth;
}
public Date getNextDay(){
try {
if(day < getMaxDaysInMonth()){
return new Date(day + 1, month, year);
}
else if(day == getMaxDaysInMonth() & month < 12){
return new Date(1, month+1, year);
}
else if(day == getMaxDaysInMonth() & month == 12){
return new Date(1, 1, year+1);
}
} catch (Exception e) {
System.out.println("You have entered an invalid Date.");
e.printStackTrace();
}
return null;
}
public int getDay(){
return day;
}
public int getMonth(){
return month;
}
public int getYear(){
return year;
}
public boolean isLeapYear(){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public String toString(){
return this.day + "." + this.month + "." + this.year;
}
}
public class NextDay {
public static void main(String args[]) throws Exception{
Date dateObj = new Date(28, 2, 2015);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}
Use a local variable and assign it and return at the end of the method and you can use jumping statements in your code if it can improve the performance
public Date getNextDay(){
Date date = new Date();
try {
if(day < getMaxDaysInMonth()){
date= new Date(day + 1, month, year);
}
else if(day == getMaxDaysInMonth() & month < 12){
date = new Date(1, month+1, year);
}
else if(day == getMaxDaysInMonth() & month == 12){
date = new Date(1, 1, year+1);
}
} catch (Exception e) {
System.out.println("You have entered an invalid Date.");
e.printStackTrace();
}
return date;
}
I would suggest you return a date in the past and avoid returning null.
I suggest to throw an exception. As part of the exception you could also give some explanation about was was/is wrong.
Returning a specific date is not a good idea, because this Date could also match to a Date that was created in a valid way. I.e. the Date 01-01-1970 can be created without any problem, right? So it should not be returned as kind or marker for a problem.
Concerning your Date representation keep in mind that you can initialize a Date with Integer.MAX_VALUE for month, day, and year. What is the expected output in this case?

Printing the rest of the calendar month after the first week

i am making a program that reads in the month 1-12 and the start day, 1-7 for sunday, monday, etc. it prints the first week fine but im having problems printing the rest of the days after the first week. it wont format the output to have a space between the rest of the days, only the first day after the first week.
side note: Keyboard is a class i have included in my project
heres my code:
import java.io.*;
public class CalendarMonth
{
static final int WEEK = 7;
public static void main(String[] args) throws IOException
{
String proceed;
char repeatCheck;
int days;
String leapYear;
char leapYearCheck;
int startDay;
do
{
days = getDays();
System.out.println(days);
System.out.println("Please enter a number 1-7 that the month starts on: (1 for sunday, 2 for monday, etc)");
startDay = Keyboard.readInt();
while(startDay < 1 || startDay > 7)
{
System.out.println("You did not enter a number 1-7, Try again: ");
startDay = Keyboard.readInt();
}
System.out.println(" s m t w th f sa");
printMonth(days,startDay);
System.out.println("\nWould you like to print another month?");
proceed = Keyboard.readString();
repeatCheck = proceed.charAt(0);
}while(repeatCheck == 'y');
}
public static int getDays() throws IOException
{
int month;
String leapYear;
int startDay;
int days = 0;
char leapYearCheck;
System.out.println("Please input a number 1-12 to print the corresponding month: ");
month = Keyboard.readInt();
while (month < 1 || month > 12)
{
System.out.println("You did not put a number 1-12, Try again: ");
month = Keyboard.readInt();
}
switch(month)
{
case 1: days = 31;
break;
case 2:
System.out.println("is it a leap year? ");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
while(leapYearCheck != 'y' && leapYearCheck != 'n')
{
System.out.println("you did not enter a yes or no answer, is it a leap year?");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
}
if (leapYearCheck == 'y')
{
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;
}
return days;
}
public static void printMonth(int days, int startDay)
{
int count;
count = startDay;
for (int counter = 1; counter <= 7; counter++)
{
if (counter < startDay)
{
System.out.print(" ");
count = count-1;
}
else
{
System.out.printf("%2d", count);
count++;
}
}
//int restOfTheMonth = (WEEK - startDay);
System.out.println();
for(int restOfTheMonth = count; restOfTheMonth <= days; restOfTheMonth++)
{
if (restOfTheMonth%WEEK==0)
{
System.out.println();
}
System.out.printf("%2d", restOfTheMonth);
}
}
}

Categories

Resources