Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to modify my class so that it passes JUnit test cases. It seems like everything should be working fine but it keeps failing. It is giving me a java.lang.AssertionError.
Here is my class
package dayofweek;
/**
* Method to find out what day of the week a certain date was
*
* Output determines what day of the week this certain date was
*
*/
public class DayOfWeek {
private int myMonth = -1, myDayOfMonth = -1, myYear= -1, myAdjustment= -1, numericDayOfWeek= -1, remainderSeven= -1;
private static final int NO_VALUE = -1;
/**
* #param what the date was
*/
public DayOfWeek(int month, int dayOfMonth, int year){
myMonth = month;
myDayOfMonth = dayOfMonth;
myYear = year;
remainderSeven = 0;
if(myMonth==1){
myAdjustment = 1;
if(myYear%4==0){
myAdjustment=0;
}
}
if(myMonth==2){
myAdjustment = 4;
if(myYear%4==0){
myAdjustment=3;
}
}
if(myMonth==3){
myAdjustment = 4;
}
if(myMonth==4){
myAdjustment = 0;
}
if(myMonth==5){
myAdjustment = 2;
}
if(myMonth==6){
myAdjustment = 5;
}
if(myMonth==7){
myAdjustment = 0;
}
if(myMonth==8){
myAdjustment = 3;
}
if(myMonth==9){
myAdjustment = 6;
}
if(myMonth==10){
myAdjustment = 1;
}
if(myMonth==11){
myAdjustment = 4;
}
if(myMonth==12){
myAdjustment = 6;
}
int fourDivides = myYear / 4;
numericDayOfWeek = myAdjustment + myDayOfMonth + (myYear-1900) + fourDivides;
remainderSeven = numericDayOfWeek % 7;
}
/**
* #return the month in a string
*/
public String getMonthString(){
String[] arrayOfMonths = new String[12];
arrayOfMonths[0] = "January";
arrayOfMonths[1] = "February";
arrayOfMonths[2] = "March";
arrayOfMonths[3] = "April";
arrayOfMonths[4] = "May";
arrayOfMonths[5] = "June";
arrayOfMonths[6] = "July";
arrayOfMonths[7] = "August";
arrayOfMonths[8] = "September";
arrayOfMonths[9] = "October";
arrayOfMonths[10] = "November";
arrayOfMonths[11] = "December";
if (this.myMonth > 0 && this.myMonth <=12){
return arrayOfMonths[this.myMonth-1];
}
else{
return null;
}
}
/**
* #return what day of the month it was
*/
public int getDayOfMonth(){
if(myDayOfMonth != NO_VALUE){
return myDayOfMonth;
}
else{
return NO_VALUE;
}
}
/**
* #return what year it was
*/
public int getYear(){
if(myYear != NO_VALUE){
return myYear;
}
else{
return NO_VALUE;
}
}
/**
* #return the numeric day of the week
*/
public int getNumericDayOfWeek(){
return remainderSeven;
}
/**
* returns what day of the week it was
*/
public String getDayOfWeek(){
String[] arrayOfDays = new String[7];
arrayOfDays[0] = "Saturday";
arrayOfDays[1] = "Sunday";
arrayOfDays[2] = "Monday";
arrayOfDays[3] = "Tuesday";
arrayOfDays[4] = "Wednesday";
arrayOfDays[5] = "Thursday";
arrayOfDays[6] = "Friday";
if( myMonth != NO_VALUE && myDayOfMonth != NO_VALUE && myYear != NO_VALUE){
return arrayOfDays[remainderSeven];
}
else{
return null;
}
}
/**
* #return the month in an int
*/
public int getMonth(){
if(myMonth != NO_VALUE){
return myMonth;
}
else return NO_VALUE;
}
}
Here is the JUnit test class
package dayofweektesting;
import dayofweek.DayOfWeek;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Test cases for "Day of week" lab assuming requirements set
* at top of DayOfWeek class
*
* Test valid leap years
*
*
*/
public class TestValidLeapYears {
/**
* Test valid 2/29/XXXX dates
*/
#Test
public void firstValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1904);
assertTrue(dow.getDayOfWeek().compareTo("Monday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 2);
}
#Test
public void secondValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1908);
assertTrue(dow.getDayOfWeek().compareTo("Saturday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 0);
}
#Test
public void thirdValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1912);
assertTrue(dow.getDayOfWeek().compareTo("Thursday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 5);
}
#Test
public void fourthValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1916);
assertTrue(dow.getDayOfWeek().compareTo("Tuesday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 3);
}
/**
* Test boundary dates of2/28/XXXX and 3/1/XXXX for valid leap years
*/
#Test
public void firstValidLeapYearBoundaries() {
DayOfWeek dow = new DayOfWeek(2, 28, 1904);
assertTrue(dow.getDayOfWeek().compareTo("Sunday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 1);
dow = new DayOfWeek(3, 1, 1904);
assertTrue(dow.getDayOfWeek().compareTo("Tuesday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 3);
}
#Test
public void secondValidLeapYearBoundaries() {
DayOfWeek dow = new DayOfWeek(2, 28, 1908);
assertTrue(dow.getDayOfWeek().compareTo("Friday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 6);
dow = new DayOfWeek(3, 1, 1908);
assertTrue(dow.getDayOfWeek().compareTo("Sunday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 1);
}
}
Here is the line the error is pointing to, in the secondValidLeapYearBoundaries()
assertTrue(dow.getDayOfWeek().compareTo("Friday") == 0);
does anyone know how to fix all these problems?
How to fix it? Print out the return value of dow.getDayOfWeek() for your failing case (or examine it in a debugger) to see what it is giving you, then single-stepping through the function to find out why. In this particular case, it's probably the constructor rather than getDayOfWeek since the latter is simply giving you information calculated by the former.
That's how you solve almost any problem, in coding and most other fields that are deterministic. Confirm that there's a problem then reexamine the steps to see where the problem was introduced.
Related
I'm using this Java code to get price based on month start and end date.
public int getPrice()
{
java.util.Date today = Calendar.getInstance().getTime();
Calendar aumgc = new GregorianCalendar();
aumgc.set(Calendar.AUGUST, 8);
aumgc.set(Calendar.DAY_OF_MONTH, 1);
java.util.Date augustStart = aumgc.getTime();
Calendar emgc = new GregorianCalendar();
emgc.set(Calendar.AUGUST, 8);
emgc.set(Calendar.DAY_OF_MONTH, 31);
java.util.Date augustEnd = emgc.getTime();
Calendar sepmgc = new GregorianCalendar();
sepmgc.set(Calendar.SEPTEMBER, 9);
sepmgc.set(Calendar.DAY_OF_MONTH, 1);
java.util.Date septemberStart = sepmgc.getTime();
Calendar eomgc = new GregorianCalendar();
eomgc.set(Calendar.SEPTEMBER, 9);
eomgc.set(Calendar.DAY_OF_MONTH, 31);
java.util.Date septemberEnd = eomgc.getTime();
Calendar ocmgc = new GregorianCalendar();
ocmgc.set(Calendar.OCTOBER, 10);
ocmgc.set(Calendar.DAY_OF_MONTH, 1);
java.util.Date octoberStart = ocmgc.getTime();
Calendar eocmgc = new GregorianCalendar();
eocmgc.set(Calendar.OCTOBER, 10);
eocmgc.set(Calendar.DAY_OF_MONTH, 31);
java.util.Date octoberEnd = eocmgc.getTime();
if (!(today.before(augustStart) || today.after(augustEnd)))
{
return 30;
}
if (!(today.before(septemberStart) || today.after(septemberEnd)))
{
return 40;
}
if (!(today.before(octoberStart) || today.after(octoberEnd)))
{
return 50;
}
return 0;
}
As you can see I'm using a lot of code to get the price based on current month. How I can simplify the code and use SQL date?
Is there any already made solution implemented in JVM?
I would suggest to use latest API LocalDateTime from Java 8 to do this king of thing, easily :
import java.time.Month; // Enum use in `switch` statement.
public int getPrice() {
LocalDateTime now = LocalDateTime.now(); // line 2
switch (now.getMonth()) { // line 3
case AUGUST:
return 30;
case SEPTEMBER:
return 40;
case OCTOBER:
return 50;
default:
return 0;
}
}
// line 2&3 can be reduce in : // switch (LocalDateTime.now().getMonth()){
This would return the same :
public int getPrice() {
return (LocalDateTime.now().getMonthValue() - 8) * 10 + 30;
}
//or return (LocalDateTime.now().getMonthValue() - 5) * 10;
This question already has answers here:
Changing YYYY/MM/DD -> MM/DD/YYYY java
(2 answers)
Closed 6 years ago.
I am inputting a specific date (dd/MM/yyyy) , while displaying it the Output is something else.
import java.text.*;
import java.io.*;
import java.util.*;
class InvalidUsernameException extends Exception //Class InvalidUsernameException
{
InvalidUsernameException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class InvalidPasswordException extends Exception //Class InvalidPasswordException
{
InvalidPasswordException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class InvalidDateException extends Exception //Class InvalidPasswordException
{
InvalidDateException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class EmailIdb1 //Class Email Id b1
{
String username, password;
int domainid;
Date dt;
EmailIdb1()
{
username = "";
domainid = 0;
password = "";
dt = new Date();
}
EmailIdb1(String u, String pwd, int did, int d, int m, int y)
{
username = u;
domainid = did;
password = pwd;
dt = new Date(y,m,d); // I think There is a problem
SimpleDateFormat formater = new SimpleDateFormat ("yyyy/MM/dd"); //Or there can be a problem
try{
if((username.equals("User")))
{
throw new InvalidUsernameException("Invalid Username");
}
else if((password.equals("123")))
{
throw new InvalidPasswordException("Invalid Password");
}
else{
System.out.println("\nSuccesfully Login on Date : "+formater.format(dt));
}
}
catch(Exception e)
{
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class EmailId //Class Email Id
{
public static void main(String args[])
{
int d,m,y,did;
String usn,pwd;
EmailIdb1 eml;
try{
usn = args[0];
pwd = args[1];
did = Integer.parseInt(args[2]);
d = Integer.parseInt(args[3]);
m = Integer.parseInt(args[4]);
y = Integer.parseInt(args[5]);
switch(m)
{
case 2: if(d==29 && y%4 == 0)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else if(d<=28 && d>=1)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else{
throw new InvalidDateException("Wrong Date.");
}
break;
case 1: case 3: case 5: case 7: case 8: case 10:
case 12: if(d>=1 && d<=31)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else
{
throw new InvalidDateException("Invalid Date");
}
break;
case 4: case 6: case 9:
case 11: if(d>=1 && d<=30)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else
{
throw new InvalidDateException("Invalid Date");
}
break;
default : throw new InvalidDateException("Invalid Date");
}
}
catch(InvalidDateException ed)
{
System.out.println(ed);
}
}
}
Me and my two friends have similar kind of problem. Don't know why This is Happening. My teacher also couldn't find what's the problem
The Output Should be
Successfully Login on Date : 1994/05/04
As the Input Is
Successfully Login on Date : 3894/06/04
First of all
new Date(int year, int month, int date)
is deprecated - you shouldn't be using it
Second of all, according to the javadoc:
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents midnight, local time, at the beginning of the day
* specified by the <code>year</code>, <code>month</code>, and
* <code>date</code> arguments.
*
* #param year the year minus 1900.
* #param month the month between 0-11.
* #param date the day of the month between 1-31.
* #see java.util.Calendar
* #deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date)</code>
* or <code>GregorianCalendar(year + 1900, month, date)</code>.
*/
So if you pass as a year 1994, you will get Date with year "3894". If you want to get "1994", you should pass 94 as a year.
And months are represented as int from range 0-11, so if you pass 5, it is formatted as "06" in your case, because 5 represents June and not May.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
public class EX02 {
public static int currentDay;
public static String result;
/**
* Constant.
* Every 3 days, feed worms.
*/
public static final int WORM_FEEDING_DAY = 3;
/**
* Constant.
* Every 5 days, bathe in sand.
*/
public static final int BATHING_DAY = 5;
/**
* Constant.
* Total number of days for which instructions are needed.
*/
public static final int NUMBER_OF_DAYS = 30;
/**
* Entry point of the program.
* #param args Arguments from command line.
*/
public static void main(String[] args) {
getInstructionForCurrentDay(currentDay);
// call and print getInstructionForCurrentDay inside a loop here
for (currentDay = 1; currentDay < NUMBER_OF_DAYS +1; currentDay++) {
currentDay = 30 - (NUMBER_OF_DAYS - currentDay);
System.out.println("DAY " + currentDay + result);
}
System.out.println("Can't fly back in time");
}
/**
* Return instruction for given day.
* #param currentDay number of day to print instructions for.
*/
public static String getInstructionForCurrentDay(int currentDay) {
if (currentDay % 3 == 0){
result = ":feed worms";
}
else if (currentDay % 5 == 0){
result = ":time to bath";
}
else if (currentDay % 5 == 0 && currentDay % 3 ==0 ){
result = ":glide";
}
else if (currentDay % 3 !=0 || currentDay % 5 != 0) {
result = ":give fruit and water";
}
return result;
}
}
Problem is that 'getInstructionForCurrentDay(int currentDay)' doesn't return wanted value inside Main method. What did I do wrong?
Your
if (currentDay % 5 == 0 && currentDay % 3 ==0 )
condition should come first, otherwise it can never be reached.
Beside that, you should assign the result of getInstructionForCurrentDay(currentDay); to some variable if you want the caller of that method to use it, and you should call getInstructionForCurrentDay(currentDay) inside the loop, since currentDay is only assigned inside the loop.
// call and print getInstructionForCurrentDay inside a loop here
for (currentDay = 1; currentDay < NUMBER_OF_DAYS +1; currentDay++) {
currentDay = 30 - (NUMBER_OF_DAYS - currentDay);
result = getInstructionForCurrentDay(currentDay);
System.out.println("DAY " + currentDay + result);
}
...
public static String getInstructionForCurrentDay(int currentDay) {
if (currentDay % 5 == 0 && currentDay % 3 ==0 ){
result = ":glide";
}
else if (currentDay % 3 == 0){
result = ":feed worms";
}
else if (currentDay % 5 == 0){
result = ":time to bath";
}
else {
result = ":give fruit and water";
}
return result;
}
You are passing currentDay into your method before it is instantiated, so you are literally passing 0 into it.
Therefore, all of your if statement conditions are never met, so result is also never given a value and thus not returning what you want.
Instead, I believe you wanted to do this:
for (currentDay = 1; currentDay < NUMBER_OF_DAYS +1; currentDay++)
{
getInstructionForCurrentDay(currentDay);
System.out.println("DAY " + currentDay + result);
currentDay = 30 - (NUMBER_OF_DAYS - currentDay);
}
Thank YOU, I solved it this way:
public class EX02 {
/**
* Constant. Every 3 days, feed worms.
*/
public static final int WORM_FEEDING_DAY = 3;
/**
* Constant. Every 5 days, bathe in sand.
*/
public static final int BATHING_DAY = 5;
/**
* Constant. Total number of days for which instructions are needed.
*/
public static final int NUMBER_OF_DAYS = 30;
/**
* Entry point of the program.
*
* #param args
* Arguments from command line.
*/
public static void main(String[] args) {
// call and print getInstructionForCurrentDay inside a loop here
if (NUMBER_OF_DAYS < 1) {
System.out.println("Can't fly back in time");
System.exit(0);
}
for (int currentDay = 1; currentDay <= NUMBER_OF_DAYS; currentDay++) {
System.out.println("Day " + currentDay + ": "
+ getInstructionForCurrentDay(currentDay));
}
}
/**
* Return instruction for given day.
*
* #param currentDay
* number of day to print instructions for.
*/
public static String getInstructionForCurrentDay(int currentDay) {
String result = "";
if (currentDay % WORM_FEEDING_DAY == 0 && currentDay % BATHING_DAY == 0)
result = "glide in wind";
else if (currentDay % WORM_FEEDING_DAY == 0)
result = "feed worms";
else if (currentDay % BATHING_DAY == 0)
result = "bathe in sand";
else
return "give fruit and water";
return result;
}
}
I have jdk java version "1.8.0_45", i am using joda time api (joda-time-2.7.jar)
By using Joda time api i am getting a wrong date.
By using Jdk 8 hijri date api i am getting a correct date.
I have a requirement to convert a gregorian date to hijri date using java api.
My sample test class is as follows:
import org.joda.time.*;
import org.joda.time.chrono.*;
import java.time.*;
import java.time.chrono.HijrahChronology;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTime dtISO = new DateTime();
System.out.println("dtISO = "+dtISO);
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance(DateTimeZone.UTC ));
System.out.println(dtIslamic.getYear()+"-" +dtIslamic.getMonthOfYear()+ "-"+ dtIslamic.getDayOfMonth());
java.time.chrono.HijrahDate hijradate = java.time.chrono.HijrahDate.now();
System.out.println("hijradate "+hijradate);
}
}
Output of this class is
C:\>java Test
dtISO = 2015-05-24T09:44:51.704+04:00
1436-8-5
hijradate Hijrah-umalqura AH 1436-08-06
Can you please tell me joda api is correct one or wrong one?
My production server has JDK1.6 i cannot upgrade it to 1.8 as of now, so kindly let me know your suggestions to get a proper hijri date .... Awaiting for your reply....
The difference you are seeing between JodaTime and JDK8 is because they use different implementations of the Hijri Calendar. There are multiple algorithms to compute (approximate) a Hijri date.
Jdk8's HijrahChoronology uses an implementation of Umm-AlQura calendar which closely matches the official Hijri calendar in Saudi Arabia as defined in http://www.ummulqura.org.sa/.
JodaTime IslamicChronology has different implementations which you can select from using its factory methods see http://joda-time.sourceforge.net/apidocs/org/joda/time/chrono/IslamicChronology.html
So it really depends on system audience. If you are in Saudi Arabia or any country which relies on UmmAlQura calendar stick with the JDK8's implementation.
i found this code on http://junaedhalim.blogspot.com/2010/01/hijri-calendar-in-java-using-kuwaiti.html hopefully it help you
import java.util.Calendar;
import java.util.Date;
/**
*
* #author junaed
*/
public class HijriCalendar
{
private int[] userDateG;
private int[] userDateH;
private WaqtMidlet midlet;
private Calendar cal;
private int currentHijriDate;
private int currentHijriMonth;
private int currentHijriYear;
public static final String[] HIJRI_MONTHS =
{
"Muharram", "Safar", "Rabi' al-awwal", "Rabi' al-thani", "Jumada al-awwal",
"Jumada al-thani", "Rajab", "Sha'aban", "Ramadan", "Shawwal", "Dhu al-Qi'dah", "Dhu al-Hijjah"
};
public static final int[] BASE_DATE_G =
{
18, 11, 2009, 0, 0
};
public static final int[] BASE_DATE_H =
{
1, 0, 1431, 0, 0
};
public HijriCalendar(WaqtMidlet midlet)
{
this.midlet = midlet;
cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
}
private void updateDefinedTime()
{
String uTimeH = midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
// String uTimeH = "";
if (uTimeH == null || uTimeH.equalsIgnoreCase(""))
{
userDateG = ApplicationConstants.BASE_DATE_G;
userDateH = ApplicationConstants.BASE_DATE_H;
}
else
{
System.out.println("uTimeH = " + uTimeH);
int date = Integer.parseInt(uTimeH.substring(0, uTimeH.indexOf(';')));
String rest = uTimeH.substring(uTimeH.indexOf(';') + 1);
int month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int hour = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int minute = Integer.parseInt(rest);
userDateH = new int[]
{
date, month, year, hour, minute
};
// String uTimeG = "";
String uTimeG = midlet.getRmsManager().getString(ApplicationConstants.RMS_GREGORIAN_DATE);
System.out.println("uTimeG = " + uTimeG);
date = Integer.parseInt(uTimeG.substring(0, uTimeG.indexOf(';')));
rest = uTimeG.substring(uTimeG.indexOf(';') + 1);
month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
userDateG = new int[]
{
date, month, year, hour, minute
};
}
cal.set(Calendar.HOUR_OF_DAY, userDateG[3]);
cal.set(Calendar.MINUTE, userDateG[4]);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.DATE, userDateG[0]);
cal.set(Calendar.MONTH, userDateG[1]);
cal.set(Calendar.YEAR, userDateG[2]);
currentHijriDate = userDateH[0];
currentHijriMonth = userDateH[1];
currentHijriYear = userDateH[2];
}
private boolean isALeapYear(int year)
{
int modValue = year % 30;
switch (modValue)
{
case 2:
return true;
case 5:
return true;
case 7:
return true;
case 10:
return true;
case 13:
return true;
case 15:
return true;
case 18:
return true;
case 21:
return true;
case 24:
return true;
case 26:
return true;
case 29:
return true;
}
return false;
}
private int getDaysInThisYear(int year)
{
if (isALeapYear(year))
{
return 355;
}
return 354;
}
public int getDaysInThisMonth(int month, int year)
{
if (month % 2 != 0)
{
return 30;
}
else
{
if (month == 12)
{
if (isALeapYear(year))
{
return 30;
}
}
return 29;
}
}
private void addOneDayToCurrentDate()
{
currentHijriDate++;
if(currentHijriDate >= 29)
{
int daysInCurrentMonth = getDaysInThisMonth(currentHijriMonth, currentHijriYear);
if( currentHijriDate > daysInCurrentMonth)
{
currentHijriDate = 1;
currentHijriMonth++;
if(currentHijriMonth > 11)
{
currentHijriMonth = 1;
currentHijriYear++;
}
}
}
}
private void addDays(long days)
{
for(long i = 0; i< days; i++)
{
addOneDayToCurrentDate();
}
}
public String getCurrentDateStr()
{
updateDefinedTime();
Date date = new Date();
// int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
long diff = date.getTime() - cal.getTime().getTime();
long days = diff / (1000 * 86400);
addDays(days);
String ret = currentHijriYear + " "+HIJRI_MONTHS[currentHijriMonth] + ", " + currentHijriDate;
return ret;
// return midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
}
}
Try using ICU4J. Its Calendar classes do not extend java.util.Calendar, but they do properly deal with Hijri dates (and many other calendar systems). I was able to get what I believe are correct results using its IslamicCalendar class, using Java 1.6.0_31:
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.IslamicCalendar;
public class HijriDate {
public static void main(String[] args) {
java.util.Calendar gregorianCal =
java.util.Calendar.getInstance(Locale.US);
System.out.printf("%tF%n", gregorianCal);
Date date = gregorianCal.getTime();
Calendar cal = new IslamicCalendar();
cal.setTime(date);
System.out.printf("%02d-%02d-%02d%n",
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH));
}
}
I have my main class Date.Java
Date.Java does:
-sets month date and year, and makes sure their valid inputs
-determines how many days are in the month you enter
-determines how many days have passed since the day you enter
-determines how many days are left from the day you enter
-determines if the year is a leap year or not
I also have a testing class TestDate.java
-It asks the user for the inputs and sends them to Date.java
My issue is I can only get the program to print the date the user enters. How would I go about calling the other methods and having them print what they are returning?
Date.java:
public class Date
{
int Day;
int Month;
int Year;
int numberOfDays;
int daysPassed;
int daysRemaining;
int M;
int D;
int Y;
public Date (int Day, int Month, int Year)
{
setDate(Month, Day, Year);
}
public void setDate (int Day, int Month, int Year)
{
setMonth(Month);
setDay(Day);
setYear(Year);
}
//-------------------SETTERS----------------------
public void setMonth(int Month)
{
M = ((Month>0&&Month<13) ?Month:1); //conditional statement that checks to see if the Month is valid
}
public void setDay(int Day)
{
D = ((Day>=1&&Day<=365) ?Day:1); //conditional statement that checks to see if the day is valid
}
public void setYear(int Year)
{
Y = ((Year>=1000&&Year<=9999) ?Year:1900); //conditional statement that checks to see if the Year is valid
}
//-------------------GETTERS----------------------
public int getMonth()
{
return M;
}
public int getDay()
{
return D;
}
public int getYear()
{
return Y;
}
public String toString()
{
return String.format("%d-%d-%d", getMonth(), getDay(), getYear());
}
public static boolean isLeapYear(int getYear)
{
if (getYear%4 == 0)
return true;
else
return false;
}
public int daysOfMonth(int getMonth, int numberOfDays, boolean isLeapYear)
{
if (getMonth==1) //jan
numberOfDays = 31;
//---------------------------------------Feb
if (isLeapYear == true) //feb
{
if (getMonth==2)
numberOfDays = 29;
}
if (isLeapYear == false) //feb
{
if (getMonth==2)
numberOfDays = 28;
}
//---------------------------------------Feb
if (getMonth==3) //march
numberOfDays = 31;
if (getMonth==4) //april
numberOfDays = 30;
if (getMonth==5) //may
numberOfDays = 31;
if (getMonth==6) //june
numberOfDays = 30;
if (getMonth==7) //july
numberOfDays = 31;
if (getMonth==8) //august
numberOfDays = 31;
if (getMonth==9) //sept
numberOfDays = 30;
if (getMonth==10) //oct
numberOfDays = 31;
if (getMonth==11) //nov
numberOfDays = 30;
if (getMonth==12) //dec
numberOfDays = 31;
return numberOfDays;
}
public int daysPassedInYear(int getMonth, int Day, int getDay, int numberOfDays, boolean isLeapYear)
{
if (getMonth==1)
Day = getDay-31;
if (isLeapYear = true)
{
if (getMonth==2)
daysPassed = (numberOfDays-getDay)-60;
if (getMonth==3)
daysPassed = (numberOfDays-getDay)-91;
if (getMonth==4)
daysPassed = (numberOfDays-getDay)-121;
if (getMonth==5)
daysPassed = (numberOfDays-getDay)-152;
if (getMonth==6)
daysPassed = (numberOfDays-getDay)-182;
if (getMonth==7)
daysPassed = (numberOfDays-getDay)-213;
if (getMonth==8)
daysPassed = (numberOfDays-getDay)-244;
if (getMonth==9)
daysPassed = (numberOfDays-getDay)-274;
if (getMonth==10)
daysPassed = (numberOfDays-getDay)-305;
if (getMonth==11)
daysPassed = (numberOfDays-getDay)-335;
if (getMonth==12)
daysPassed = (numberOfDays-getDay)-366;
}
if (isLeapYear = false)
{
if (getMonth==2)
daysPassed = (numberOfDays-getDay)-59;
if (getMonth==3)
daysPassed = (numberOfDays-getDay)-90;
if (getMonth==4)
daysPassed = (numberOfDays-getDay)-120;
if (getMonth==5)
daysPassed = (numberOfDays-getDay)-151;
if (getMonth==6)
daysPassed = (numberOfDays-getDay)-181;
if (getMonth==7)
daysPassed = (numberOfDays-getDay)-212;
if (getMonth==8)
daysPassed = (numberOfDays-getDay)-243;
if (getMonth==9)
daysPassed = (numberOfDays-getDay)-273;
if (getMonth==10)
daysPassed = (numberOfDays-getDay)-304;
if (getMonth==11)
daysPassed = (numberOfDays-getDay)-334;
if (getMonth==12)
daysPassed = (numberOfDays-getDay)-365;
}
return daysPassed;
}
public int daysRemainingInYear(int dayspassed, boolean isLeapYear, int daysRemaining)
{
if (isLeapYear = true)
daysRemaining = (366 - dayspassed);
if (isLeapYear = false)
daysRemaining = (365 - dayspassed);
return daysRemaining;
}
}
TestDate.java:
import javax.swing.JOptionPane;
public class TestDate {
public static void main(String[] args) {
int month =Integer.parseInt(JOptionPane.showInputDialog("What month do you want(in number form ex. Jan = 1?"));
int day =Integer.parseInt(JOptionPane.showInputDialog("What day do you want within the month?"));
int year =Integer.parseInt(JOptionPane.showInputDialog("What year do you want"));
Date setDateObject = new Date(month, day, year);
System.out.println(setDateObject.toString());
}
}
You can call the other methods on your Date object and print their return value.
Date date = new Date(1, 2, 2003);
System.out.println(date.getYear());
System.out.println(date.isLeapYear());
The way you use parameters is weird.. Parameters like getMonth, numberOfDays, isLeapYear are used to pass information into the function. getMonth and isLeapYear are essential to the function working correctly, but numberOfDays is not essential. You can declare the function like so:
public int daysOfMonth(int getMonth, boolean isLeapYear)
{
if (getMonth==1) //jan
return 31;
//---------------------------------------Feb
if (isLeapYear && getMonth==2)
return 29;
}
if (/* !isLeapYear && */ getMonth==2)
return 29;
}
//---------------------------------------Feb
if (getMonth==3) //march
return 31;
if (getMonth==4) //april
return 30;
if (getMonth==5) //may
return 31;
if (getMonth==6) //june
return 30;
if (getMonth==7) //july
return 31;
if (getMonth==8) //august
return 31;
if (getMonth==9) //sept
return 30;
if (getMonth==10) //oct
return 31;
if (getMonth==11) //nov
return 30;
if (getMonth==12) //dec
return 31;
return -1; // error
}
Then you can create a date like so and call the daysOfMonth function.
Date date = (2, 29, 2004);
System.out.println(date);
System.out.println("Is this date a leap year? " + date.isLeapYear());
System.out.println("How many days in this month? " + date.daysOfMonth(date.getMonth(), date.isLeapYear());
Do
System.out.println(yourobject.yourMethod());
This will print what ever your method yourMethod() is returning.
Also you can print the values inside any function.
public void yourMethod(){
System.out.println(yourAtrribute);
}
For your class you may do as following:
Date setDateObject = new Date(month, day, year);
//do other stuffs here
System.out.println(setDateObject.getYear());
This will print year that your getYear() method is returning.