[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

Need help in java

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 36
Thread images: 3

File: 7JOskDw.png (137KB, 1280x544px) Image search: [Google]
7JOskDw.png
137KB, 1280x544px
I'm trying to set up a class that receives a date and if it's not a valid date sets it to 1/1/2000 (among other things it does)

So let's say this is how I check if it's valid

[code]private static int numDaysInMonth(int month, boolean isLeapYear)
{
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear)
{
return 29;
} else
{
return 28;
}
default:
return 0;
}
}

public static boolean isLeapYear(int year)
{
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}

public static boolean isValidDate(int month, int day, int year)
{
return (month >= 1 && month <= 12) && (day >= 1 && day <= numDaysInMonth(month, isLeapYear(year))) && (year >= 0 && year <= maxYear);
}[/code]

And these are my constructors for the Date object

[code]public Date(int day, int month, int year)
{
_day = day;
_month = month;
_year = year;
}

// Additional constructor
public Date(Date date)
{
_day = date._day
_month = date._month
_year = date._year
}[/code]

How do I "fuse" them so that every date I receive is checked to be valid and reset to 1/1/2000 if not, as a private method within the same class?
>>
Didn't realize you can't write code on this board

https://codetidy.com/9783/
>>
>>232780
// this looks like Java, but it's pseudocode.
Date parseDefaultDate(Date dd, String s) {
SimpleDateFormat sdf = new SimpleDateFormat ("MM/dd/yy", Locale.ENGLISH);
Date d = sdf.parse(s);
if (d == null) d = dd;
return d;
}

Date DefaultDate = new Date (946728000) // Noon GMT, 1/1/2000. You could also use a DateFormat as above.

Date parsedDate = parseDefaultDate(DefaultDate, "43/1/2017");
system.out.println (parsedDate.toString()); // 1/1/2000

parsedDate = parseDefaultDate(DefaultDate, "12/1/2017");
system.out.println (parsedDate.toString()); // 12/1/2017


Don't try to write your own date handling code. The API provides it, and producing date handling code that works correctly all the time is a massive undertaking, comparable in workload to a whole Android app.
>>
>>232784
I'm not allowed to use that for the homewor, have to write my own Date class
>>
File: 200_s[1].gif (46KB, 356x200px) Image search: [Google]
200_s[1].gif
46KB, 356x200px
>>232785
At the very least use the API's technique of returning a Date if valid or a null if not valid, and then you can put the "parsing a date" code in one method and the "turning invalid dates into default dates" code into another that calls it.
>>
>>232789
What i'm confused is how to do it all within the same class

Like I have the constructor

public Date(int day, int month, int year)
{
_day = day;
_month = month;
_year = year;
}

How do I make sure that any date I receive is valid and if not change it to the default? Do I do it within the brackets of this constructor?
>>
Do a check in the constructors.

If (isValidDateisValidDate)(day,month,year) ){
_day = day;
_month = month;
_year = year;
}else{
_day = 1;
_month = 1;
_year = 2000;
}


If you don't need access to isValidDate() outside the Date class, then make it private.
Then just create the Date object with the parameters (day,month,year) they will be changed if invalid
>>
>>232795
Is it enough to just have this somewhere in the class as a private method?

Also, shouldn't it be if (isValidDate(this.date) )

or something like that? I don't know how to address a private method
>>
>>232791
Don't do any of that. The very most you should do is have an isValid() method. The date class is for storing dates, not manipulating them.

Add a static method* parseDate(String s) that parses dates out of strings, then you can go:

FakeDate fd = FakeDate.parseDate("1/2/3456");
if (!fd.isValid) {fd=new FakeDate(1,1,2001);}


* it's static, because the task of parsing a date has absolutely nothing whatsoever to do with any of the instance variables. No matter what date your class is holding, the string should be parsed exactly the same way, and therefore the parsing method should be static.
>>
>>232801
and

class DefaultFakeDate extends FakeDate {
public DefaultFakeDate(int day, int month, int year) {
_day = day;
_month = month;
_year = year;
if (!self.isValid()) {_day=1;_month=1;_year=2000;}
}
}
>>
>>232796
>(isValidDate(this.date) )
Your method is this
>public static boolean isValidDate(int month, int day, int year)
so you'd access them by this._month according to your constructor.

The Date class needs to contain private month,day,year like
>Class Date(stuff here){
>private int _month
>private int _day
>private int _year

>Date constructors
>private checking methods

>}//end Date class

Then change the constructors,

public Date(int day, int month, int year){

If (isValidDateisValidDate(day,month,year) ){
_day = day;
_month = month;
_year = year;
}else{
_day = 1;
_month = 1;
_year = 2000;
}

}

This way all methods are private and only accessed through the constructors

Add a public method to get the date. something like
>public string getDate(){
//assemble string here
}
OR
3 seperate public functions like:
public int getDay{
return _day
}
>>
>>232801
>>232802
I think I lost you man

>>232803
Why is "isValidDate" written twice like that?

Do the checking methods have to be written abovet he constructors or does it not matter?

Also is the way I wrote it even proper for a private method? Do I need to change anything about it to put it in a class like I'm doing now? I only started working with classes so that's why I'm asking.
>>
>>232807
>Why is "isValidDate" written twice like that?
oops, typo
>Do the checking methods have to be written abovet he constructors or does it not matter?
don't think it matters
>Also is the way I wrote it even proper for a private method?
The only difference between private and public is where it can be used from, so it's fine
>Do I need to change anything about it to put it in a class like I'm doing now?
Just make eveything private that doesn't need to be used from outside the class

The purpose of the class is to encapsulate data and the methods that manipulate it.
From outside the class (like in main()) you only have access to the constructors and public methods. Can't set the day dirrectly but only through public methods that validate it.
>>
>>232809
I also have methods to setDay, setMonth, setYear

If it the setDay it recieves for example is wrong (like 32) then it's supposed to stay the same (instead of going to 1/1/2000)


Is this the right way to go about it?

public void setDay(int dayToSet)
{
if(isValidDate(dayToSet, this._month, this._year))
{
_day = dayToSet;
}
}

This would do no changes to _day if the resulting date is invalid, right?

Also, is it correct to address the month and year values by this._month and this._year and the day value I'm checking as dayToSet ?


Thanks for the help so far btw
>>
>>232810
So what's it supposed to do if I call

d.setDay(31);
then
d.setMonth(2);

or

d=new date(2,2,2015);
d.setDay(31);
d.setMonth(1);


In any case, you'll need to split out isValid() into isValidDay(), isValidMonth(), and isValidYear, the isValid() becomes
boolean isValid() {return(isValidDay()&&isValidMonth()&&isValidYear());}

Which you probably should be doing anyway.

Splitting isValidDay into isValidDayValue() and isValidDayForMonthAndYear() would probably be a good idea too.
>>
>This would do no changes to _day if the resulting date is invalid, right?
you got it
>Also, is it correct to address the month and year values by this._month and this._year and the day value I'm checking as dayToSet ?
yes
The only time you'd have to use this._day is to avoid clashes
For example:
public setDay(int _day){
//here the local variable _day is the one that was passed
//to access the class member _day you need to use
this._day
}

But in the above, if the passed variable has a different name like dy then the class variable can be accessed by either _day or this._day
>>
>>232813
It's not possible to just use the isValidDate method in the way I did?
>>
>>232815
The structure is fine (didn't check logic)
That anon is just breaking up the checks into seperate checks, but you already covered it with this:

public void setDay(int dayToSet)
{
if(isValidDate(dayToSet, this._month, this._year))
{
_day = dayToSet;
}
}
>>
>>232820
Got it

Another question:

I'm not allowed to add my own private attributes, but I'm allowed to add finals

But if I add a final MIN_YEAR and MAX_YEAR (for my date validity check) it tells me a non-static variable can't be refernced from a static context.

Not sure what it means, but is it okay to make the final static? I don't remember doing this before with finals.


Also I need to create a method that returns the difference in days between a given date and the date being worked on and I have no idea how to even begin on this one.
>>
>>232825
You can combine static and final.

Final: can't be changed once set.
Static: is the same for all instances, can be accessed without going through an instance

Constants are usually public static final, except if there's no possible reason another class could ever need to access them. There's not much point in them being not public, because they're final, and if another class really really wanted them, they could just copy them out the bytecode.
>>
>>232825
You should probably have read the entire spec before you started.

If you'd used a single int to represent the number of days since the first day of MIN_YEAR, then all the get_whatever and is_valid_whatever would have been the same amount of work, and comparing two dates would be as complicated as a single subtraction.
>>
>>232831
Good point... but idk how to do that at this point or how to convert it to that now

>>232829
Also I just tried setting up a tester to see if my validity check works and it doesn't seem to work...

I tried this

public class DateTester
{


public static void main(String[] args) {
Date d1=new Date(5,5,19994);
System.out.println("day of d1:"+d1.getDay());
}
}

And it just returns 5 as if it's a valid date

so Idk what to do.
>>
>>232837
For reference this is how I wrote it in the class for the relevant constructor

public Date(int day, int month, int year)
{
if(isValidDate(day, month, year) == false)
{
_day = 1;
_month = 1;
_year = 2000;
}
_day = day;
_month = month;
_year = year;
}
>>
>>232838
>>232837
Okay I think I realized my mistake? I needed to add an 'else'

I thought those aren't mandatory if it's just one if?
>>
>>232831
Reading this again, idk if I'm even allowed to do that since I'm not allowed to set my own private attributes, only finals or temporary variables inside of methods
>>
>>232840
If you're not allowed to store the date, how are you supoosed to store the date?
>>
>>232839
They're not mandatory.

If you want to conditionally run the code that's in the if(){}, then always run the code after it, then write it the way you wrote it.
>>
>>232841
I don't know how to convert it to a number and then use that throughout the whole thing without adding a new int
>>
>>232842
The way I wrote it clearly didn't work (it allowed me to have an invalid date) and after I added an else it worked.
>>
>>232844
Sure.

Doesn't mean your code's invalid or wrong, though, just that it wasn't doing what you thought it did.
>>
>>232846
I guess that's a logical way of looking at it
thx for all the help


Trying to write a method for difference calculation without using loops now..fug

Also apparently this isn't a valid way to turn it into a string so idk what I'm doing wrong yet again

public String toString() {
return _day +"/" + _month + "/" + _year;
}
>>
>>232847
You need to cast your ints into Strings.

I'm pretty sure Java has java.io.printf now, unless you're not allowed to use that either.
>>
>>232847
>Trying to write a method for difference calculation without using loops now..fug
Yeah, you kinda painted yourself into a corner here.

static int DayOfYear (int d, int m, int y) {
if (m > 1) d+= 31
if (m > 2) d+= 28
if (m > 3) d+= 31
if (m > 4) d+= 30
if (m > 5) d+= 31
if (m > 6) d+= 30
if (m > 7) d+= 31
if (m > 8) d+= 31
if (m > 9) d+= 30
if (m > 10) d+= 31
if (m > 11) d+= 30
if (isLeapYear(d,m,y) && m>2) d++;
return d;
}

static int DaysBetweenDates (MyDate d1, MyDate d2) {
int days1 = DayOfYear(d1) + 365*d1.getYear();
int days2 = DayOfYear(d1) + 365*d1.getYear();
return days1-day2+LeapYearsBetweenDates(d1,d2);
}

static int LeapYearsBetweenDates (MyDate d1, MyDate d2) {
/* Good fucking luck with this one */
/* Especially if you're "not allowed" to use a loop */
}
>>
File: ttt.jpg (24KB, 433x130px) Image search: [Google]
ttt.jpg
24KB, 433x130px
>>232859
It turns out I had a closing } before the new method I added so that was the problem.

It seems to work now, idk about what you said.
>>
>>232865
kek

I just realized they gave us a calculation for days since the start of the gregorian calendar

so I think I can use that as a method and then the difference method will use it

Also it's supposed to be a received date + the date that is currently the object so like

d1.difference(d2);

Would end up using calculateDate on both and detracting one from the other to know the difference but also turning any negative number into a positive one (not allowed to have -100 day difference, only 100)

Brain hurts too much atm
>>
>>232869
>it's supposed to be a received date + the date that is currently the object

public static int difference (MyDate d1, MyDate d2) {
/* calculate difference between d1 and d2 */
}

int difference (MyDate d2) {
return difference(self,d2);
}

>(not allowed to have -100 day difference, only 100)
return Math.abs(dstsotgc1 - dstsotgc2);
Thread posts: 36
Thread images: 3


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.