Comparison methods - Page 2


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 35

Thread: Comparison methods

  1. #16
    Join Date
    Mar 2005
    Posts
    20
    Just please keep in mind that I don't want to use techniques that haven't been covered yet.

    Requirements:
    -A Temperature class.
    -Two parameters, a temperature value (floating-point) number and a character for the scale, either 'C' or 'F'.
    - Four constructor methods, one for each instance variable (assume zero degrees if no value isspecified and C if no scale is specified, one with two parameters for the two instance variables, and a default constructor (set to zero degrees Celsius).
    - Two accesor methods, one to return the temperature in C and one to return the temperature in F, using the formulas from the textbook, and round to the nearest tenth of a degree.
    - Three reset methods, one to set the value, one to set the scale ('F' or 'C') and one to set both.
    -Three comparison methods, one to test whether two temperatures are equal, one to test whether one temperature is greater than another, and one to test whether one temperature is less than another.
    -A driver program that tests all the methods.
    -Use each of th constructors, include at least one true and one false case for each of th comparison methods, and test at least the following temperature equalities: 0.0 degrees C = 32.0 degrees F, -40.0 degrees C = -40.0 degrees F, and 100.0 degrees C = 212 degrees F.


    Thanks,
    Eric

  2. #17
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Quote Originally Posted by ericelysia1
    Let's do it.
    Oh, fine. I knew it!
    Quote Originally Posted by ericelysia1
    The homework was due on Sunday, March 6. Right now, it is Tuesday Morning 7:35am (I'm on Guam).
    Ooops. So wrt the homework we're quite late I guess... But the more I'm convinced you mean it, right?
    Quote Originally Posted by ericelysia1
    Just please keep in mind that I don't want to use techniques that haven't been covered yet.
    Believe me, I do. As well as I do know your requirements by now. As said before, you'll have to give me some credit, ie. trust me in that I can anticipate what you should think about next

    The point is: you're in fact already employing techniques that haven't been covered in your text book/course yet. It's just that you sort of don't have a name for'em right now and can't really express them in java. All I'm trying to show you is just about how to organize these ideas you seem to have developped on your own in a way that fits into "OO-thinking" or "java-thinking" - as you like.

    Ok, I have thought about how to get this crash-course going and set up an abstract class "AbstractTemperature" to get going and to have a common start. Now I realized, that you might not know what an abstract class is
    Well, I'm too tired now to turn it another way. So I'm just posting this abstract class and ask you to extend it. But don't bother, it's not as complicated as you might think. Just write
    Code:
    public class Temperature extends AbstractTemperature {
      // constructors here - use methods setValue(...), setScale(...), set(...)
      public char getScale() {
        // ...
      }
      // and all other methods that have "abstract" in their signature in the abstract class
    }
    With this abstract class I give you a head-start; in particular read the comments above the abstract methods and think about the already implemented method toString() - it's a one-liner...
    It's not necessary to fill in real code in all the methods that are abstract in AbstractTemperature (you would fill in in class Temperature, not the abstract class!); just get it to compile without errors. All you have to do is replicate the signature of the abstract methods without the keyword "abstract" and where the return type is other than "void" just write "return 0;" or "return null;" as a dummy. This you do (just to emphasize it once more) in the class Temperature, NOT in AbstractTemperature, which you simply adopt as it is.
    Also don't bother about "static" and "final" if you don't understand 'em. You will understand them later.

    If you like, you can try to override (ie. implement in Temperature) the methods getScale() and setScale(char). After that you might do set(double, char). Do it in this order, if you do. We may discuss the semantics of the methods later. But if you just get the class "Temperature" to compile without errors and read the comments, it's perfectly fine.

    In either case you may add a main method to Temperature as a first test:
    Code:
    public static void main(String[] args) {
      Temperature t1 = new Temperature();
      System.out.println( t1 );
    }
    This may give you an idea of what toString() is for.

    So here's AbstractTemperature:
    Code:
    public abstract class AbstractTemperature {
    
      public static final char SCALE_CELSIUS    = 'c';
      public static final char SCALE_FAHRENHEIT = 'f';
    
      public static String getScaleName(char scale) {
        switch (scale) {
          case SCALE_CELSIUS:    return "Celsius";
          case SCALE_FAHRENHEIT: return "Fahrenheit";
          default:
            System.err.println("unknown scale '" + scale + "'");
            System.exit(1);
        }
        return null;
      }
    
      //round method returns the value rounded to tenths
      public static double roundToTenths(double value) {
        return Math.round(value * 10.0)/10.0;
      }
    
      public static double convert(double val, char fromScale, char toScale) {
        throw new UnsupportedOperationException("Sorry, not yet implemented");
      }
    
    
      protected double value = 0.0;
      protected char   scale = SCALE_CELSIUS;
    
    
      public abstract char   getScale();
    
      /** Returns the value of this Temperature object as a value of the given scale.
        */
      public abstract double getValue(char scale);
    
    
      /** Sets the scale in which this temperature is measured to the given scale
        * and also the value of the temperature (according to this scale).
        */
      public abstract void set(double value, char scale);
    
    
      /** Sets the scale with respect to which the attribute value is to
        * be interpreted. The attribute value itself remains unchanged.
        */
      public abstract void   setScale(char scale);
    
      /** Sets the temperature value, interpreted in the given scale.
        * Note that the actual object's attribute "scale" remains unchanged
        * and that only the object's attribute "value" will be appropriately
        * adjusted according to the actual object's attribute "scale".
        */
      public abstract void   setValue(double value, char scale);
    
      /** Returns a string representation of this temperature
        * including the scale wrt wich the value is to be interpreted.
        */
      public String toString() {
        return value + " " + getScaleName(scale);
      }
    
      /** Returns -1, 0 or +1
        * as the temperature represented by this object 
        * is less than, equal to, or greater than
        * the temperature represented by the specified object.
        */
      public abstract int compareTo(AbstractTemperature t);
    
    }
    CU tomorrow


    p.s. I'm in Germany, so I guess our times are not quite compatible, are they?
    Last edited by meisl; 03-07-2005 at 09:56 PM.

  3. #18
    Join Date
    Mar 2005
    Posts
    20
    Germany? We just moved from Germany (in August). We were there for 3 years.

    Anyways, I just wanted to touch base. I have printed out what you posted. I will create an AbstractTemperature class and I will get it to compile without errors. Once I get this done, I will post it (if that's what you want me to do).

    I wanted to get to it today, but I have been working a proposal, which is my last assignment for my technical writing class. I finished the proposal and turned it in.

    Since you wanted me to be completely honest, I just want you to know that I turned in the Temperature program that I was working on the other night. I worked on it all day Sunday, Monday, and Tuesday (my time) and turned it in. I don't know if it will get a good grade or not.

    The point is, I still want to go through this little crash-course with you, so don't assume that you have wasted any of your time. I want to understand the reasons and principles of the methods.

    I'll post the class tomorrow. Thanks! Eric

  4. #19
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Hey, that's cool

    Just to make sure: you're NOT supposed to make any changes to the class AbstractTemperature. You only use it, ie. refer to it in ANOTHER file called Temperature.java which will contain a new class Temperature; i mean: not the one you handed in but one you start over writing now.
    You can (and should) start writing Temperature by extending* the first code snippet in my last post. There you fill in dummy methods as described.
    Then you try to compile the whole stuff, ie.:
    Code:
    javac AbstractTemperature.java Temperature.java
    in the directory where these two files are.

    *note: "extending" here I used NOT in the sense of how Temperature "extends" AbstractTemperature. Don't get confused; just take it literally this time: "add some text to...".

    If the compiler complains about class Temperature, you have to look over it again. Maybe you forgot a method or so. Just try to follow my description in the last post, even if you don't understand what all that "abstract", "final" etc. is for, ok?

    If the compiler complains about class AbstractTemperature, this is a BUG in the crash-course and should not happen! Please let me know in such case.

    If all compiles without errors, you can go ahead and add the main method I gave in the second code snippet (again, you add only to class Temperature).
    Compile again and let it run:
    Code:
    java Temperature
    The output will be
    Code:
    0.0 Celsius
    Can you figure out how this works?

    When this is done, we can proceed with the next chapter.


    Being honest/the handed in class:
    Hey, you really worked hard and what you handed in is ok for your course (if you ask me). As already pointed out, I'd even say that you had some ideas that go beyond what has been covered in your course yet. So it's a small wonder that you can't express them appropriately by now.
    And by "honest", I simply mean that if I ask something like "Do you know why this or that is so or so?" and you don't - you say so. And, in case, that you do ask if you feel uncertain about some thing.

    So long

    ----
    p.s.: I'm gonna get back here tomorrow night since I gotta work.

    p.p.s.: Don't worry too much about that abstract class. It's only for the purpose of our little crash-course. This way we can keep requirements and hints separated from what is work in progress. Normally one would do it in just one class.
    Last edited by meisl; 03-09-2005 at 08:34 AM.

  5. #20
    Join Date
    May 2004
    Posts
    37
    OK, before I get too far into this, I want to make sure I am understand you correctly. Here is the code that I now have. I haven't added the main to it yet. This compiles with no errors.

    Code:
    package Temperature;
    
    public class Temperature //extends AbstractTemperature
    { // constructors here - use methods setValue(...), setScale(...), set(...) 
    
    	  public char getScale() 
    	  { // ... 
    			return 0;
         } // and all other methods that have "abstract" in their signature in the abstract class 
    	
     
         /** Returns the value of this Temperature object as a value of the given scale.
         */
         public double getValue(char scale)
    	  {
    			return 0;
    	  }
         /** Sets the scale in which this temperature is measured to the given scale
         * and also the value of the temperature (according to this scale).
         */
    	  public void set(double value, char scale)
         {
    	
         }
         /** Sets the scale with respect to which the attribute value is to
         * be interpreted. The attribute value itself remains unchanged.
         */
     	  public void setScale(char scale)
    	  {
      
     	  }
    	  /** Sets the temperature value, interpreted in the given scale.
     	  * Note that the actual object's attribute "scale" remains unchanged
     	  * and that only the object's attribute "value" will be appropriately
      	  * adjusted according to the actual object's attribute "scale".
      		*/
    	  public void setValue(double value, char scale)
    	  {
      
    	  }
    	  /** Returns a string representation of this temperature
      	  * including the scale wrt wich the value is to be interpreted.
      	  */
    	  public String toString() 
     	  {
    	  		return null;
      	  		//return value + " " + getScaleName(scale);
      	  }
      	  /** Returns -1, 0 or +1
         * as the temperature represented by this object 
         * is less than, equal to, or greater than
         * the temperature represented by the specified object.
         */
     	  public int compareTo(/*Abstract*/Temperature t)
         {
      			return 0;
      	  }
     }
    I haven't learned about "Abstract" or "extends" yet.

    If I am doing this right, let me know and I will move on. I did compile the Abstract and I got no errors. What do you mean by "java Temperature" and how do you get 0.0 Celsius?

  6. #21
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100

    first step is made

    Yep, a first step is made. And it's good that you ask.
    Now there are some points I did not expect and that I'd like to comment on.
    So that you know what I'm talking about, I'm gonna quote portions of the code wherein I use comments like
    Code:
    // ...
    // some comment I added to give you a hint
    which are NOT intended to be included in the real code.
    Quote Originally Posted by ericelysia
    Code:
    package Temperature;
    
    public class Temperature //extends AbstractTemperature
    { // constructors here - use methods setValue(...), setScale(...), set(...) 
    
    	  public char getScale() { // ... 
    			return 0;
         } // and all other methods that have "abstract" in their signature in the abstract class 
     
         /** Returns the value of this Temperature object as a value of the given scale.
         */
    
          // ... 
    
         /** Sets the scale in which this temperature is measured to the given scale
         * and also the value of the temperature (according to this scale).
         */
    
          // ... 
    
    	  public String toString() {
    	  		return null;
      	  		//return value + " " + getScaleName(scale);
      	  }
    
          // ... 
    
    	  public int compareTo(/*Abstract*/Temperature t) {
      			return 0;
      	  }
      }
    Pretty pied, eh?
    Ok, now for the agenda:

    1. package
    -----------------
    Although it's a good idea to introduce a new package where our little project goes, I had decided not to do so - in order to not complicate things (it definitely would, at least communication).
    But if you insist on that, we can do it. Then I'd suggest we use lower case for the package name and we should (although in fact, we need not) put AbstractTemperature into this package, ie. add the same package statement to it (exceptionally!) and have it in the same directory (name of which must be the name of the package) as Temperature.
    Currently I have a directory called "temperatureTut" where the files are in and where I invoke the compiler and the interpreter. This is only to fight chaos and has nothing to do with packages.
    BTW:
    Code:
    java Temperature
    (on the command line) simply invokes the interpreter and tells it to run the class Temperature. You have done this sort of thing earlier on, haven't you?


    2. //extends AbstractTemperature
    //return value + " " + getScaleName(scale); in toString()
    public int compareTo(/*Abstract*/Temperature t) {
    -----------------
    Once the two classes ARE in the same package - be it "temperature", or, as I would prefer, just the default package, ie. no package statement at all - you can uncomment these and it will compile.
    That way the class Temperature can "inherit" from class AbstractTemperature. This is what "abstract" and "extends" are for. You will better understand what that means later.


    3. green / blue comments
    -----------------
    Remove all the comments that are like the green ones above from your class Temperature.
    Also remove all the blue-like comments from your class Temperature but DO NOT REMOVE them from class AbstractTemperature.
    I'd like to show you a *very* cool thing, maybe you have already heard of it. Try
    Code:
    javadoc -d doc *.java
    on the command line in the directory "temperatureTut" or whatever you called it. Remember: by now I still assume both classes in the default package!
    After that has finished, a directory "temperatureTut/doc" will have been created and inside it you will find a file "index.html". Watch it with your web-browser. Try to find there the documentation for eg. Temperature.getValue(...).


    4. return 0; in getScale()
    -----------------
    Question: the return type of getScale() is char. The 0 you return is an integer (int). Even so, why does this work?


    5. Assignment
    -----------------
    After you have solved the package problem, add the main method and let it run from the command line. Do you get "0.0 Celsius" as the output?


    Hope I did not discourage you too much You're making progress anyhow.

    So, long
    Last edited by meisl; 03-12-2005 at 10:32 PM.

  7. #22
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Hey, just one more thing I just realized:

    You said you would not want to have a toString() in your class Temperature...
    Hence I set things up such that you DO NOT NEED toString() in your class Temperature. Alas, as I just figured out, you have added such a method.
    Well, it's not really a problem so all that has been said remains valid. Yet toString() in Temperature is simply not necessary. I recommend that you delete it from Temperature.

  8. #23
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Hmm, little crash course seems to have suffered some premature crash...

  9. #24
    Join Date
    May 2004
    Posts
    37

    Just a temporary delay

    My apologies. We have had a medical situation in my family. My wife and 3 1/2 month old son were medically evacuated to Hawaii this morning so that my son can be seen at a NICU. We have been trying to get everything ready for their trip. During the chaos, I have also been swamped with Computer and Systems Architecture homework.

    I have not forgotten about this progam; it has been on my mind. I will try to catch up on it over the next day or two. If you want to let this go, I understand. I can always post questions along the way throughtout the rest of my course. But if you are ok with the delay, I will make every attempt to jump back into it.

    Just let me know what is more convienent to you.

    Thank you,
    Eric

  10. #25
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Oh, I am sorry to hear that. How is your son now? Hope it's nothing too serious (don't know what a NICU is).

    As for the delay: that's okay, just wasn't sure if you were still interested. You can read over the last few posts and send your class Temperature when you've got time.
    If possible, I'd like to speed things up a bit then for this is kind of an exercise for me too. But don't worry, I consider this speeding-up my job, not yours (well, it still depends on you...).

    Best wishes
    Last edited by meisl; 03-24-2005 at 07:24 PM.

  11. #26
    Join Date
    May 2004
    Posts
    37

    I won't quit.

    OK, vielen dank! Sorry about the acronym NICU (Neonatal Intensive Care Unit). Anyways, I will try to catch up then in the next day or two.

  12. #27
    Join Date
    May 2004
    Posts
    37

    Hate to do this.

    Unfortunately, due to my circumstances, I am not going to be able to continue with this lesson. I am very sorry that this is the outcome. I am having to watch my two other children all day without any help and the homework just keeps getting piled on. I still have my head above water, but I am trying to eliminate any extra activity right now. If it wasn't for my unfortunate situation, I would continue.

    I will still continue to post questions about my homework and future programming projects.

    I am sincerely thankful for the time that you set aside.

    Eric

  13. #28
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100

    Aargh!

    Oh, again I'm sorry to hear that.

    See, in the beginning I meant it to become a thing of an hour or two, just the two of us posting some five messages each or so. Then I saw that this was not quite adequate and arranged for some days. Then...

    Ok, I'll stop that! It's just that I don't see the problem, ie. if you're doing your homework and going to post questions about it, you could as well take the course and get your future homework done in at least half the time - promise! It is NOT that complicated.

    Anyway, I'll post the class Temperature I had expected so far (only expected a skeleton) and summarize the questions/assignments
    Code:
    public class Temperature extends AbstractTemperature {
    
      public char getScale() {
        return scale; // return 0; would've been okay as well
      }
    
      public void setScale(char scale) {
      }
    
      public double getValue(char scale) {
        return 0.0;
      }
    
      public void setValue(double value, char scale) {
      }
    
      public void set(double value, char scale) {
      }
    
      public int compareTo(AbstractTemperature other) {
        return 0;
      }
    
      public static void main(String[] args) {
        Temperature t1 = new Temperature();
        System.out.println( t1 );
      }
    
    }
    Left to do:
    ---------------
    0. compile the whole ****.

    1. type
    Code:
    java Temperature
    on the command line. See what happens. Note that there is no method toString() in Temperature. So where does this output come from?

    2. type
    Code:
    javadoc -d doc *.java
    on the command line. Then open the newly created file doc/index.html in your browser and click (at least twice clicks necessary) until you found some text on eg. Temperature.getValue(...). There it says Description copied from class: AbstractTemperature and some more. Cool or what?

    3. (possibly) return 0; in getScale()
    The return type of getScale() is char. The 0 you return is an integer (int). Even so, why does this work? Otherwise, if you have return scale; there, why could THAT work (...since there's no attribute scale in Temperature)?


    --
    p.s.: next time I'm gonna say that anybody should feel free to take over your place, eric.
    Last edited by meisl; 03-28-2005 at 07:20 PM.

  14. #29
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Ok, next is now.
    But hmm, to be honest I'm afraid this crash-course had a crash-start into its short life anyway...

  15. #30
    Join Date
    May 2005
    Posts
    5

    New Member (Temperature Class)

    Hi, I too am struggling with this Temperature Class. Can you help?

    Here is the assignment:

    Write a Temperature class that has two parameters: a temperature value (a floating-point number) and a character for the scale, either C for Celsius or F for Fahrenheit. The class should have four constructor methods: one for each instance variable (assume zero degrees if no value is specified and Celsius if no scale is specified), one with two parameters for the two instance variables, and a default constructor (set to zero degrees Celsius). Include (1) two accessor methods to return the temperature, one to return the degrees Celsius, the other to return the degrees Fahrenheit use the *formulas* from Programming Project 2 of Chapter 3 to write the two methods, and round to the nearest tenth of a degree; (2) three reset methods, one to set the value, one to set the scale (F or C), and one to set both; and (3) three comparison methods, one to test whether two temperatures are equal, one to test whether one temperature is greater than another, and one to test whether one temperature is less than another. Then write a driver program that tests all the methods. Be sure to use each of the constructors, to include at least one true and one false case for each of the comparison methods, and to test at least the following temperature equalities: 0.0 degrees C = 32.0 degrees F, -40.0 degrees C= -40.0 degrees F, and 100.0 degrees C = 212.0 degrees F.

    *degreesC = 5(degreesF - 32)/9*
    *degreesF = (9(degreesC)/5) + 32*

    Here is the class definition that I created:

    PHP Code:
    public class Temperature//Class name

    {
            
    double temp;//Variable

            
    char scale;//Varible

            
    public Temperature()//Default Constructor
            
    {
                
    temp 0;
                
    scale 'C';
            }

            public 
    Temperature(char tempScale)//Scale Constructor
            
    {
                
    temp 0;
                
    scale tempScale;
            }

            public 
    Temperature(double tempValue)//Temp Constructor
            
    {
                
    temp tempValue;
                
    scale 'C';
            }

            public 
    Temperaturedouble tempValuechar tempScale)//Constructor
            
    {
                
    temp tempValue;
                
    scale tempScale;
            }

            public 
    double getC()//Used to get degrees C
            
    {
                
    double value;
                if (
    scale == 'C')
                {
                    return 
    temp;
                }
                else
                {
                    return  ((double)(
    Math.round((5*(temp 32.0)/9.0)*10.0))/10);
                }
            }

            public 
    double getF()//Used to get degrees F
            
    {
                if (
    scale == 'F')
                {
                    return 
    temp;
                }
                else
                {
                    return (
    Math.round((9*(temp/5) + 32)*10)/10);
                }
            }

            public 
    void setTemp(double newTemp)//set temp
            
    {
                
    temp newTemp;
            }

            public 
    void setScale(char newScale)//set scale
            
    {
                
    scale newScale;
            }

            public 
    void setTempScale(double newTempchar newScale)//set both
            
    {
                
    temp newTemp;
                
    scale newScale;
            }

            public 
    boolean equals(Temperature obj)//compares for equality
            
    {
                return (
    getC() == obj.getC());
            }

            
    // This is comparing statements to see if the first is greater than the second
            
    public boolean greaterThan(Temperature obj)
            {
                return (
    getC() > obj.getC());
            }

            
    // This is comparing  statements to see if the first is less than the second
            
    public boolean lessThan(Temperature obj)
            {
                return (
    getC() < obj.getC());
            }

            
    // Returns temp value
            
    public double getTemperatureTemp()
            {
                return 
    temp;
            }

            
    // Returns scale character
            
    public char getTemperatureScale()
            {
                return 
    scale;
            }
        } 
    Additional Information:

    PHP Code:
    Temperature
    # value: double
    # scale: char
    Temperature( )
    Temperature(double valueIn)
    Temperature(char scaleIn)
    Temperature(double valueInchar scaleIn)
    getF( ):double
    getC( ):double
    reset(double valueIn): void
    reset(char scaleIn): void
    reset(double valueInchar scaleIn): void
    equals(Temperature objIn): Boolean
    lessThan(Temperature objIn): Boolean
    greaterThan(Temperature objIn): Boolean


    public double getC( )
    {
        
    double result=0.0;
        if (
    scale == 'C')
            
    result value;
        if (
    scale == 'F')
            
    result 5.0*(value  32.0)/9.0;
        
    result Math.round(result 10)/10
        
    return result;
    }

    public 
    boolean equals(Temperature obj)
    {
        return (
    obj.getC() == this.getC());

    My question is, is the class definition correct?
    Need help creating the driver class.

    Thanks,
    ~Jo (EST)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center