Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help on understanding this code

 
Stacey Johnson
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,
Here I am agian struggling to figure things out. Right now I am trying to understand this class and test program to go with. I just don't understand how it works. Can anyone take a look at it and give me some insight. In my assignment I'm suppose to use the following class (Rational Class) and write a program thta will compute a summation series as follows:
1/1 + 1/2 + 1/3 +... +1/n
1/1 + 1/2 + 1/2exponent2 +...+ 1/2exponentn
So I figure I need a better understanding of this class before I attempt a program for the above.
One other thing is can someone explain the "tostring()" method to me?
The Rational Class is as follows:

And the testprogram:

Thanks
Stacey
 
Carlos Failde
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Tutorial

Object contains the toString method, which returns a String object containing the name of the object's class and its hash code. Most, if not all, classes will want to override this method and print out something meaningful for that class.



toString()

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.


The above class overrides toString to return a representation of a rational nubmer.
Incidentally the println's in TestRationalClass could have been simplified:

as the toString() method is automatically invoked when you concatenate an object and a string
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic