Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / May 2004

Tip: Looking for answers? Try searching our database.

Value not being passed properly..

Thread view: 
Jim - 16 May 2004 01:14 GMT
For some reason Im having a problem passing the value of n out of the
getEasterSundayDay() method.
If I do a return n in the getEasterSundayDay() method I get the month value
correctly.  But when use n in the switch statement it comes back a 0
everytime and returning emonth comes back as "Error3"..any ideas?..thanks

Ive been told this is the reason but I dont understand:

The problem is occurring because you are setting the day instance value when
you call the getEasterSundayDay() method.  However, you are attempting to
use the value in the getEasterSundayMonth() method BEFORE it has been set by
the day method.

You should calculate the month and day in the object's constructor and set
the instance data to these known values in the constructor (before anyone
else has a change to call any of the accessor methods).  This will prevent
this kind of problem from happening.

Heres my code:

//Main Class
import cs1.Keyboard;

public class Assignment1_Master
{
public static void main(String[] args)
{
int year;
do
{
EasterSunday es = new EasterSunday();
System.out.print("Determine Easter Sunday for what year:");
year = Keyboard.readInt();
es.setEasterSundayYear( year);
if (year > 0)
System.out.println("In " + es.getEasterSundayYear() + " Easter Sunday
falls/fell on " + es.getEasterSundayMonth() + ", " + es.getEasterSundayDay()
+ ".");
else
System.out.println ("Goodbye!");
}while(year > 0);
}
}
//Secondary Class
public class EasterSunday
{
private int y;
//Initialized to "Error1" for debugging if n is not properly passed from
getEasterSundayDay()
private String emonth = "Error1";
private int n;
public void setEasterSundayYear( int year)
{
y = year;
}
public int getEasterSundayYear()
{
//Returns the year entered by the User
return y;
}
public int getEasterSundayDay()
{
//Implementation of the Gauss algorithm
int a = y % 19;
int b = y / 100;
int c = y % 100;
int d = b/4;
int e = b % 4;
int g = (8 * b + 13 )/25;
int h = (19 * a + b - d - g + 15 )%30;
int j = c / 4;
int k = c % 4;
int m = (a + 11 * h) / 319;
int r = (2 * e + 2 * j - k - h + m + 32) % 7;
n = (h - m + r + 90) / 25;
int p = (h - m + r + n + 19) % 32;
//Returns the day that Easter falls on that year
return p;
}
public String getEasterSundayMonth()
{
//Assigns a month name according to the value of n
switch (n)
{
case 0: emonth= "Error3"; break;
case 1: emonth="January"; break;
case 2: emonth ="February"; break;
case 3: emonth ="March"; break;
case 4: emonth ="April"; break;
case 5: emonth ="May"; break;
case 6: emonth ="June"; break;
case 7: emonth ="July"; break;
case 8: emonth ="August"; break;
case 9: emonth ="September"; break;
case 10: emonth ="October"; break;
case 11: emonth ="November"; break;
case 12: emonth ="December"; break;
}
return emonth;
}
}
Ryan Stewart - 16 May 2004 02:16 GMT
> For some reason Im having a problem passing the value of n out of the
> getEasterSundayDay() method.
[quoted text clipped - 97 lines]
> }
> }

That's extremely hard to read. Please try to incorporate some indentation in
your posts in the future. Your problem restated is this: your "private int
n" is a member of your EasterSunday class. Okay so far, except that's a
horribly non-descriptive variable name. Anyway, your getEasterSundayMonth
method uses "n" in a switch to set your emonth variable, right? Here's the
working portion of your main method adjusted to comply with standards:

EasterSunday es = new EasterSunday();
System.out.print("Determine Easter Sunday for what year:");
year = Keyboard.readInt();
es.setEasterSundayYear(year);
if (year > 0) {
   System.out.println("In " + es.getEasterSundayYear() + " Easter Sunday
falls/fell on " + es.getEasterSundayMonth() + ", " + es.getEasterSundayDay()
+ ".");
} else {
   System.out.println ("Goodbye!");
}

So, read through that and see what happens. My comments are, well, commented
:-)

EasterSunday es = new EasterSunday();
// Create an instance of EasterSunday. Okay so far.

System.out.print("Determine Easter Sunday for what year:");
year = Keyboard.readInt();
// Presumably, this works and gives you a year as an int.

es.setEasterSundayYear(year);
// This causes the "y" member of your "es" instance to be set to whatever
was entered above.

if (year > 0) {
   ... // <-- Covered below
} else {
   System.out.println ("Goodbye!");
}
// This structure allows you to exit the program, yes?

System.out.println("In " + es.getEasterSundayYear() + " Easter Sunday
falls/fell on " + es.getEasterSundayMonth() + ", " + es.getEasterSundayDay()
+ ".");
(No more "//" now.) Here's your problem line. First, realize that the +
operator is evaluated left to right. You probably know this intuitively but
may not realize how it's impacting your program here. So everything in the
parentheses is evaluated starting with "In ". String literal. Easy. Then we
append whatever is returned by es.getEasterSundayYear() to that. Looking in
that method, all it does is return the value of the variable "y", which was
set above by a call to the setEasterSundayYear method. Next we append
another String literal, and then we append what is returned by
es.getEasterSundayMonth(). What does this method do? Based on the value of
the member variable "n", it returns a particular String. So what is the
value of the variable "n" at this point? Well, up to now you've done nothing
to set it, so it still has its initial value of 0. Therefore the method
returns the String "Error3", as expected. So what's the root problem? You
never set "n" before you try to use it. Then where *do* you set it? Take a
look. The only place I see is in the getEasterSundayDay method. That means
that you *must* call getEasterSundayDay() before you call
getEasterSundayMonth(). Taking it a step further, it means that your
EasterSunday object is in an invalid state until you call the
getEasterSundayDay method. That shouldn't happen. A constructor should
produce a valid object. Order of method invocation should have no bearing
whatever.
Oscar kind - 16 May 2004 07:45 GMT
> For some reason Im having a problem passing the value of n out of the
> getEasterSundayDay() method.
[...]
> Ive been told this is the reason but I dont understand:
>
[quoted text clipped - 7 lines]
> else has a change to call any of the accessor methods).  This will prevent
> this kind of problem from happening.

When you create the EasterSunday object, the member variable "n" is
initialized to 0 (because it is an int; if it were an Integer would have
been null). Then you use that value of "n" in getEasterSundayMonth().
This is wrong, because you mean it to represent a month number in the
range 1-12. Only after that, you call getEasterSundayDay() which, as a
side effect, initializes "n" correctly. This is too late.

What happens it you move the calculations from getEasterSundayDay() to the
constructor?
- You need to introduce the member variable "p" to return it in
 getEasterSundayDay().
- Just after you create the object, it contains the correct values for
 year, month and day. The constructor initializes a valid object.
- The method getEasterSundayDay() works as most programmers expect a
 "get...()" method to work: it doesn't change the object.

When you write code, try to do the following:

- Read SUN's Java Code Conventions, and apply them to all Java code you
 write. They're followed by all Java developers I've read code from, and
 allow for easily readable code.

 Note: Aside from variable names and indentation, you already followed
 these conventions in the code in your post. Well done.

- Your code should always create valid objects. So in every class that has
 a non-trivial state (such as EasterSunday), the constructor should
 finish the initialization or throw an exception.

- Never create methods with side effects. They always confuse at least one
 programmer on any team (not infrequently the one who wrote it), and
 introduce more difficult bugs (debugging methods with side effects is a
 pain).

kind regards,
Oscar

Signature

Oscar Kind                                    http://home.hccnet.nl/okind/
Software Developer                    for contact information, see website

PGP Key fingerprint:    91F3 6C72 F465 5E98 C246  61D9 2C32 8E24 097B B4E2

Andrew Thompson - 16 May 2004 08:26 GMT
> - Read SUN's Java Code Conventions,

...errr.  Do you mean *Sun* there?  
It is not an acronym.

[ I was about to question the capital 'C's
as well ..but that is how Sun puts it. ]

>..and apply them to all Java code you write.

An excellent idea.  I like to think I do,
and went in search of Sun's guide.
Found the online version here..
<http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html>

Linked to from the download/formats page..
<http://java.sun.com/docs/codeconv/>
( Interestingly, the .zip download of the
HTML version is 62Kb! )

>   Note: Aside from variable names ..

<http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html>

>..and indentation,

<http://java.sun.com/docs/codeconv/html/CodeConventions.doc3.html>

..well (shrugs) while I was there..    ;-)

Signature

Andrew Thompson
http://www.PhySci.org/ Open-source software suite
http://www.PhySci.org/codes/ Web & IT Help
http://www.1point1C.org/ Science & Technology



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.