Comparison methods - Page 3


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 3 of 3 FirstFirst 123
Results 31 to 35 of 35

Thread: Comparison methods

  1. #31
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Looks OK to me.

    But, since you posted it here I couldn't resist adding/tweaking it a bit

    Among the useless things I did was renaming getC and GetF, mostly
    because getC rings like an age old io function to me...

    Code:
    import java.util.*;
    import java.text.*;
    /**
     * A sortable, formatted and printable temperature class
     *
     */
    public class Temperature implements Comparator   { //Class name
      /**
       * format for printing temperature values
       */
      static DecimalFormat df=new DecimalFormat("0.0");
      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 Temperature(double tempValue, char tempScale) { //Constructor
        temp = tempValue;
        scale = tempScale;
      }
    
      public double getCelsius() { //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 getFarenheit() { //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 newTemp, char newScale) { //set both
        temp = newTemp;
        scale = newScale;
      }
      /**
       * return a formatted temperature string
       * @return
       */
      public String toString () {
        return df.format(temp)+" "+scale;
      }
      /**
       * the equals method should be implemented as an override of the
       * Object class' equals method, parameter should be an Object.
       * Note: the two next metods define the Comparator interface
       * Among othjer things this enables sorting.
       * @param obj
       * @return
       */
      public boolean equals(Object obj) { //compares for equality
        if (!(obj instanceof Temperature)) {
          return false;
        }
        Temperature aTemp=(Temperature)obj;
        return (getCelsius() == aTemp.getCelsius());
      }
      /**
       * Method used by  Collections.sort
       * @param o1
       * @param o2
       * @return
       */
      public int compare(Object o1, Object o2) {
        Temperature t1=(Temperature)o1;
        Temperature t2=(Temperature)o2;
        // switch t1 & t2 here to get descending sort
        return (int)(t1.getCelsius()*10.0d-t2.getCelsius()*10.0d);
      }
      // This is comparing statements to see if the first is greater than the second
      public boolean greaterThan(Temperature obj) {
        return (getCelsius() > obj.getCelsius());
      }
    
      // This is comparing  statements to see if the first is less than the second
      public boolean lessThan(Temperature obj) {
        return (getCelsius() < obj.getCelsius());
      }
    
      // Returns temp value
      public double getTemperatureTemp() {
        return temp;
      }
    
      // Returns scale character
      public char getTemperatureScale() {
        return scale;
      }
    
      public static void main(String[] args) {
        Temperature t = new Temperature(100.5, 'C');
        System.out.println("\n\nt:"+t);
        // stuff an arrayList with temperatures and sort them on actual heat value
        ArrayList tList=new ArrayList();
        tList.add(t);
        tList.add(new Temperature(140.5,'F'));
        tList.add(new Temperature(60,'C'));
        tList.add(new Temperature(90,'F'));
        tList.add(new Temperature(70.3,'C'));
        tList.add(new Temperature(.7,'C'));
        // the 'new Temperature()' parameter here is just a dummy for using the
        // Temperature class' Comparator
        Collections.sort(tList,new Temperature());
        System.out.println("Sorted temperatures");
        for (int i=0; i<tList.size(); i++) {
          System.out.println(tList.get(i));
        }
      }
    }
    eschew obfuscation

  2. #32
    Join Date
    May 2005
    Posts
    5

    TemperatureDemo

    Cool! Thanks for your response.

    The outcome is not exactly what the assignment calls for.

    Recap of Assignment:
    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 Celsius = 32.0 degrees Fahrenheit, -40.0 degrees Celsius= -40.0 degrees Fahrenheit, and 100.0 degrees Celsius = 212.0 degrees Fahrenheit.

    Below is incomplete code for my driver program. I am not sure which methods to invoke to test the temperatures for equality, greater than or less than.
    Can you help?

    PHP Code:
     public class TemperatureDemo
     
    {
         public static 
    void main (String[] args)
         {
            
    //Instantiate temp object
            
    Temperature temp = new Temperature();

            
    //invoke methods
            
    temp.getCelsius();
            
    temp.getFarenheit();

            
    System.out.println("Testing Temperature Class");

            
    System.out.print("0.0 degrees C is ");
            
    //what method will determine = to, > than or < than ???
            
    System.out.print("(equal to, greater than or less than)");
            
    System.out.println(" 32.0 degrees F");

            
    System.out.print("-40.0 degrees C is ");
            
    //what method will determine = to, > than or < than ???
            
    System.out.print("(equal to, greater than or less than)");
            
    System.out.println(" -40.0 degrees F");

            
    System.out.print("100.0 degrees C is ");
            
    //what method will determine = to, > than or < than ???
            
    System.out.print("(equal to, greater than or less than)");
            
    System.out.println(" 212.0 degrees F");
         {

        }
      }


  3. #33
    Join Date
    May 2005
    Posts
    5

    Can anybody help me out here?

    My final is tomorrow and I still have another assignment to complete. I know that's not your problem, just looking for some help with this TemperatureDemo. A few hints would help.

    I think I have to invoke the following methods to get the result the assignment calls for:

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

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

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

      
    // Returns scale character
      
    public char getTemperatureScale() {
        return 
    scale;
      } 
    Am I close?
    Thanks,
    ~Jo

  4. #34
    Join Date
    May 2005
    Posts
    5

    Driver Template

    I found the Driver Template. I'm going to try to figure it out.


    PHP Code:
    public class TempDriver
    {
       ...

       
    Temperature t1=new Temperature();
       
    Temperature t2=new Temperature(32.0);
       
    Temperature t3=new Temperature('C');
       
    Temperature t4=new Temperature(75.5'F');


       if (
    t1.equals(t2))
          
    System.out.println("Temperature 1 is equal to temperature 2.");
       else
          
    System.out.println("Temperature 1 is not equal to temperature 2."); 

  5. #35
    Join Date
    May 2005
    Posts
    5

    Calculator Class - Mathematical Equations???

    I have modified this program from a simple "adding machine" and changed it to perform subtraction, multiplication & division however I have not studied any mathematical equations yet. Does anyone know how to make the Subtract, Multiply & Divide buttons work properly on this application?


    PHP Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    /**
     GUI for adding, subtractin, multiplying and dividing
     a series of numbers.
    */
    public class Calculator extends JFrame implements ActionListener
    {
        public static final 
    int WIDTH 400;
        public static final 
    int HEIGHT 200;

        private 
    JTextField inputOutputField;
        private 
    double sum 0;
        private 
    double difference 0;
        private 
    double product 0;
        private 
    double quotient 0;

        public static 
    void main(String[] args)
        {
            
    Calculator guiCalculator = new Calculator( );
            
    guiCalculator.setVisible(true);
        }

        public 
    Calculator( )
        {
            
    setTitle("Simple Calculator");
            
    addWindowListener(new WindowDestroyer( ));
            
    setSize(WIDTHHEIGHT);
            
    Container contentPane getContentPane( );
            
    contentPane.setLayout(new BorderLayout( ));

            
    JPanel buttonPanel = new JPanel( );
            
    buttonPanel.setBackground(Color.GRAY);
            
    buttonPanel.setLayout(new FlowLayout( ));
            
    JButton addButton = new JButton("Add");
            
    addButton.addActionListener(this);
            
    buttonPanel.add(addButton);
            
    JButton subtractButton = new JButton("Subtract");
            
    subtractButton.addActionListener(this);
            
    buttonPanel.add(subtractButton);
            
    JButton multiplyButton = new JButton("Multiply");
            
    multiplyButton.addActionListener(this);
            
    buttonPanel.add(multiplyButton);
            
    JButton divideButton = new JButton("Divide");
            
    divideButton.addActionListener(this);
            
    buttonPanel.add(divideButton);
            
    JButton resetButton = new JButton("Reset");
            
    resetButton.addActionListener(this);
            
    buttonPanel.add(resetButton);
            
    contentPane.add(buttonPanelBorderLayout.SOUTH);

            
    JPanel textPanel = new JPanel( );
            
    textPanel.setBackground(Color.BLUE);
            
    textPanel.setLayout(new FlowLayout( ));

            
    inputOutputField = new JTextField("Numbers go here."30);
            
    inputOutputField.setBackground(Color.WHITE);
            
    textPanel.add(inputOutputField);
            
    contentPane.add(textPanelBorderLayout.CENTER);
        }

        public 
    void actionPerformed(ActionEvent e)
        {
            if (
    e.getActionCommand( ).equals("Add"))
            {
                
    sum sum +
                    
    stringToDouble(inputOutputField.getText( ));
                
    inputOutputField.setText(Double.toString(sum));
            }
            else if (
    e.getActionCommand( ).equals("Subtract"))
            {
                     
    difference =
                     
    stringToDouble(inputOutputField.getText());
                     
    inputOutputField.setText(Double.toString(difference));
            }
            else if (
    e.getActionCommand( ).equals("Multiply"))
            {
                        
    product =
                            
    stringToDouble(inputOutputField.getText( ));
                        
    inputOutputField.setText(Double.toString(product));
            }
            else if (
    e.getActionCommand( ).equals("Divide"))
            {
                        
    quotient =
                            
    stringToDouble(inputOutputField.getText( ));
                        
    inputOutputField.setText(Double.toString(quotient));
            }
            else if (
    e.getActionCommand( ).equals("Reset"))
            {
                
    sum 0;
                
    inputOutputField.setText("0.0");
            }
            else
                
    inputOutputField.setText("Error in adder code.");
         }

        private static 
    double stringToDouble(String stringObject)
        {
            return 
    Double.parseDouble(stringObject.trim( ));
        }


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