Comparison methods


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 35

Thread: Comparison methods

Hybrid View

  1. #1
    Join Date
    Mar 2005
    Posts
    20

    Comparison methods

    Hello,

    I am working on a program for school. I am required to have the methods that are in my program. I also need to add three comparison methods to it. I just want to make sure I am on the right track before I attempt the comparison methods.
    Thanks,
    Eric

    Here is what I have so far.

    Code:
    public class TestTemp
    {
    //Two parameters, a temperature value (a floating-point number) 
    //and a character for the scale, either 'C' for Celsius or 'F'
    //for Fahrenheit.
    	private double tempValue;	//in degrees
    	private char tempScale;		//in either 'C' or 'F'	
    
    		
    //-------------------------------------------------------------------------
    public void writeOutput()
    {
    	System.out.println("The temperature is " + (tempValue) + " degrees " + tempScale + ".");
    }
    
    //-------------------------------------------------------------------------		
    //Four constructor methods, one for each instance variable, 
    //(assume zero degrees if no value isspecified and Celsius
    // if no scale is specified), one with two parameters for the
    //two instance variables, and a default constructor (set to
    //zero degreees Celsius.
    
    	//----------------------------------------------------------------------
    	//constructor method for the instance variable tempValue
    	public TestTemp(double initialTempValue)
    	{
    		tempScale = 'C';
    		if(initialTempValue < 0)
    		{
    			System.out.println("Error:  Negative temperature value.");
    			System.exit(0);
    		}
    		else
    		{	
    			round(initialTempValue);
    			tempValue = initialTempValue;
    		}
    	}
    	
    	//----------------------------------------------------------------------
    	//constructor method for the instance variable tempScale
    	public TestTemp(char initialTempScale)
    	{
    		tempValue = 0;
    		
    		initialTempScale = Character.toUpperCase(initialTempScale);
    		if(initialTempScale == 'C' || initialTempScale == 'F')
    		{
    			tempScale = initialTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			System.exit(0);
    		}
    	}
    	
    	//----------------------------------------------------------------------
    	//constructor method for both instance variables tempValue and tempScale
    	public TestTemp(double initialTempValue, char initialTempScale)
    	{
    		if(initialTempValue < 0)
    		{
    			System.out.println("Error:  Negative temperature value.");
    			System.exit(0);
    		}
    		else
    		{
    			round(initialTempValue);
    			tempValue = initialTempValue;
    		}
    		
    		
    		initialTempScale = Character.toUpperCase(initialTempScale);
    		if(initialTempScale == 'C' || initialTempScale == 'F')
    		{
    			tempScale = initialTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			System.exit(0);
    		}
    	}
    	
    	//----------------------------------------------------------------------		
    	//default constructor method
    	public TestTemp()
    	{
    		tempValue = 0.0;
    		tempScale = 'C';	
    	}		
    
    //----------------------------------------------------------------------
    	//Two accessor (get) methods, one to return the degrees Celsius,
    	//and one to return the degrees Fahrenheit.
    	//Round to the nearest tenth of a degree.
    	
    	//accessor method to return the degrees Fahrenheit.
    	public double getF()
    	{
    		if(tempScale == 'F')
    		{
    			System.out.println("Error:  The temp scale is already Fahrenheit.");
    			return 0;
    		}
    		else
    		{
    			double tempF;
    			tempF = ((9 * tempValue)/5 + 32);  //tempF = ((9*tempC)/5 + 32)
    			tempValue = tempF;
    			tempScale = 'F';
    			round(tempValue);
    			return tempF;		
    		}		
    	}
    	
    	//accessor method to return the degrees Celsius
    	public double getC()
    	{	
    		if(tempScale == 'C')
    		{
    			System.out.println("Error:  The temp scale is already Celsius.");
    			return 0;
    		}
    		else
    		{
    			double tempC;
    			tempC = (5 * (tempValue - 32)/9);			//tempC = 5*(tempF - 32)/9
    			tempValue = tempC;
    			tempScale = 'C';
    			round(tempValue);
    			return tempC;	
    		}	
    	}
    	
    	//------------------------------------------------------------------------
    	//round method returns the tempValue rounded to tenths
    	public double round(double roundTempValue)
    	{
    		tempValue = Math.round(tempValue * 10.0)/10.0;
    		return tempValue;
    	}
    
    //-------------------------------------------------------------------------
    //Three reset methods, one to reset the value, one to reset the 
    //scale ('F' or 'C'), and one to reset both the value and the scale.
    
    	//----------------------------------------------------------------------
    	//reset method to reset tempValue
    	public void set(double newTempValue)
    	{
    		if(newTempValue < 0)
    		{
    			System.out.println("Error:  Negative temperature value.");
    			System.exit(0);
    		}
    		else
    		{
    			round(newTempValue);
    			tempValue = newTempValue;
    			
    		}
    		//tempScale is unchanged
    	}
    	
    	//----------------------------------------------------------------------
    	//reset method to reset tempScale
    	public void set(char newTempScale)
    	{
    		newTempScale = Character.toUpperCase(newTempScale);
    		if(newTempScale == 'C' || newTempScale == 'F')
    		{
    			tempScale = newTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			System.exit(0);
    		}
    		//tempValue is unchanged
    	}
    	
    	//----------------------------------------------------------------------
    	//reset method to reset tempValue and tempScale
    	public void set(double newTempValue, char newTempScale)
    	{
    		if(newTempValue < 0)
    		{
    			System.out.println("Error:  Negative temperature value.");
    			System.exit(0);
    		}
    		else
    		{
    			round(newTempValue);
    			tempValue = newTempValue;
    		}
    		newTempScale = Character.toUpperCase(newTempScale);
    		if(newTempScale == 'C' || newTempScale == 'F')
    		{
    			tempScale = newTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			System.exit(0);
    		}
    		//tempValue and tempScale are reset
    	}
    	
    	
    	
    //------------------------------------------------------------------------
    /*
    	public static boolean equals(TestTemp otherTemp)
    	{
    		initialTempScale = Character.toUpperCase(initialTempScale);
    		return((this.tempValue == otherTemp.tempValue) && (this.tempScale == otherTemp.tempScale));
    	}
    */	
    	
    }
    
    //-------------------------------------------------------------------------	
    //Driver program that tests all the methods.
    //Use each one of the constructors.
    //Include at least one true and one false
    //case for each of the comparison methods.
    //Test the following:  
    //		0.0 degrees C = 32 degrees F
    //		-40 degrees C = -40 degrees F
    //		100 degrees C = 212 degrees F	
    
    public class TestTempDriver
    {
    	public static void main(String[] args)
    	{
    		
    	
    		//t1, t2, t3, and t4 test the four constructors
    		TestTemp t1 = new TestTemp();
        	             t1.writeOutput();
    	             TestTemp t2 = new TestTemp(22.222);
    		t2.writeOutput();
    		TestTemp t3 = new TestTemp('f');
    		t3.writeOutput();
    		TestTemp t4 = new TestTemp(44.444, 'f');
    		t4.writeOutput();
    		
    		//t5 tests the set method with both the double and char parameters
    		TestTemp t5 = new TestTemp(55.555, 'f');
    		System.out.println("The initial temp for t5 is:");
                             t5.writeOutput();		
    		System.out.println("Please enter the correct temp:");
                             double correctTemp = SavitchIn.readLineDouble( );
                             System.out.println("Please enter the correct temp scale:");
                             char correctScale = SavitchIn.readLineNonwhiteChar( );
                             t5.set(correctTemp, correctScale);
    		System.out.println("The updated temp for t5 is:");
                             t5.writeOutput();		
    		
    		//t6 tests the set method with the double parameter
    		TestTemp t6 = new TestTemp(66.666, 'f');
    		System.out.println("The initial temp for t6 is:");
                             t6.writeOutput();
    		System.out.println("Please enter the correct temp:");
                             correctTemp = SavitchIn.readLineDouble( );
                             t6.set(correctTemp);
    		System.out.println("The updated temp for t6 is:");
                             t6.writeOutput();
    		
    		//t7 tests the set method with the char parameter
    		TestTemp t7 = new TestTemp(77.777, 'f');
    		System.out.println("The initial temp for t7 is:");
                              t7.writeOutput();
                              System.out.println("Please enter the correct temp scale:");
                              correctScale = SavitchIn.readLineNonwhiteChar( );
                              t7.set(correctScale);
    		System.out.println("The updated temp for t7 is:");
                             t7.writeOutput();
    		
    		
    		*/
    		
    		//t8 tests the getF accessor method
    		TestTemp t8 = new TestTemp();	
    		double convertTemp = 88.888;
    		char convertScale = 'c';
    		t8.set(convertTemp, convertScale);
    		t8.getF();	
    		t8.writeOutput();
    		
    		//t9 tests the getC accessor method
    		TestTemp t9 = new TestTemp();
    		convertTemp = 99.999;
    		convertScale = 'f';
    		t9.set(convertTemp, convertScale);
    		t9.getC();	
    		t9.writeOutput();
    		
    		
    		//t10 tests the equals comparison method
    		TestTemp t10 = new TestTemp(1010.10, 'f');
    		double testValueEqual = 1010.10;
    		char testScaleEqual = 'f';
    		t10.set(testValueEqual, testScaleEqual);
    		t10.equals(t10);
    		t10.writeOutput();
    		
    		
    		TestTemp t11 = new TestTemp(5, 'f');
    		TestTemp t12 = new TestTemp(5, 'f');
    		
    		if(t11 == t12)
    		{
    			System.out.println("Match with ==.");
    		}
    		else
    		{
    			System.out.println("Do Not match with ==.");
    		}
    			
    		if(t11.equals(t12))
    		{
    			System.out.println("Match with the method equals.");
    		}
    		else
    		{
    			System.out.println("Do Not match with the method equals.");
    		}
    		
    		
    		
    		
    		
    		/*
    	
    		System.out.println("Press Enter key to end program.");
    		String junk;
    		junk = SavitchIn.readLine();
    	
    		*/
        }
    }

  2. #2
    Join Date
    Mar 2005
    Posts
    20

    Please Help With Comparison Methods

    Now, I am trying to implement three comparison methods. I am not quite sure if I am doing it right, because when I test for equality, the two values are always equal. Maybe I am just not writing the driver (main) correctly. Here is my code:

    Code:
    //---------------------------------------------------------------------
    
    //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.	
    //----------------------------------------------------------------------
    
    //comparison method to test whether two temperatures are equal.
    public boolean equals(TestTemp otherTemp)
    {	
    return(this.tempValue == (otherTemp.getC()));
    }	
    //----------------------------------------------------------------------
    
    //comparison method to test whether one temperatures is greater than another.
    public boolean greaterThan(TestTemp otherTemp)
    {	
    return(this.tempValue > (otherTemp.getC()));
    }	
    //----------------------------------------------------------------------
    
    //comparison method to test whether one temperature is less than another.
    public boolean lessThan(TestTemp otherTemp)
    {	
    return(this.tempValue < (otherTemp.getC()));
    } 
    //----------------------------------------------
    //----------------------------------------------
    //Here is the code from my driver
    TestTemp t10 = new TestTemp();
    TestTemp t11 = new TestTemp();
    double test1ValueEqual = 0.0;
    char test1ScaleEqual = 'c';
    double test2ValueEqual = 32.0;
    char test2ScaleEqual = 'f';
    t10.set(test1ValueEqual, test1ScaleEqual);
    t11.set(test2ValueEqual, test2ScaleEqual);		
    if(t10.equals(t11))
    {	
    System.out.println("0.0 degrees C is equal to 32 degrees F.");
    }
    else
    {	
    System.out.println("0.0 degrees C is not equal to 32 degrees F.");
    }
    		
    TestTemp t12 = new TestTemp(0.0, 'c');
    TestTemp t13 = new TestTemp(35.0, 'f');
    double test3ValueEqual = 0.0;
    char test3ScaleEqual = 'c';
    double test4ValueEqual = 35.0;
    char test4ScaleEqual = 'f';
    t12.set(test1ValueEqual, test1ScaleEqual);
    t13.set(test2ValueEqual, test2ScaleEqual);		
    if(t12.equals(t13))
    {	
    System.out.println("0.0 degrees C is equal to 35 degrees F.");
    }
    else
    {	
    System.out.println("0.0 degrees C is not equal to 35 degrees F.");
    }
    						
    TestTemp t14 = new TestTemp();
    TestTemp t15 = new TestTemp();
    double test1ValueLessThan = 18.5;
    char test1ScaleLessThan = 'c';
    double test2ValueLessThan = 137.9;
    char test2ScaleLessThan = 'f';
    t14.set(test1ValueLessThan, test1ScaleLessThan);
    t15.set(test2ValueLessThan, test2ScaleLessThan);		
    if(t14.lessThan(t15))
    {	
    System.out.println("18.5 degrees C is less than 137.9 degrees F.");
    }
    else
    {	
    System.out.println("18.5 degrees C is not less than 137.9 degrees F.");
    }
    Thanks,
    Eric

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Just a couple of things: If you want to override the java.lang.Object method
    equals you must duplicate its methods signature completely, like

    public boolean equals (Object ob).

    So if you do implement it for the famed class 'MyClass' you do like:

    Code:
    public boolean equals (Object ob) {
      if (!(ob instanceof MyClass)) return false; // not even a MyClass
      // the next lines assumes that there is a getName method in MyClass that
      // return a string value that is unique for a MyClass instance, It could be
      // a numeric value, a set of values and so on...
      MyClass aMyClass=(MyClass)ob;
      return this.getName().equals(aMyClass.getName());
    }
    Implemented this way, all other java classes that checks for the containment
    of specific objects (like Vectors, ArrayLists, Hashtables) will do their search according
    to the conditions set in the equals methos of your class.

    Finally: you cannot use the '==' operator for comparing Strings, '==' used on
    objects will just compare the pointer address values, use the equals() method for
    Strings (and other objects).
    Last edited by sjalle; 03-06-2005 at 07:50 PM.
    eschew obfuscation

  4. #4
    Join Date
    Mar 2005
    Posts
    20
    I am not familiar with the famed class 'MyClass'. It is not in my textbook.

    I am not sure I understand everything that you are doing here.

    In my code, If I change this:
    Code:
    public boolean equals(TestTemp otherTemp)
    {
    	return(this.tempValue == (otherTemp.getC()));
    }
    and make it this:
    Code:
    public boolean equals(TestTemp otherTemp)
    {
    	return(this.equals(otherTemp.getC()));
    }
    I get an error that states: double cannot be dereferenced.


    Thank you,
    Eric

  5. #5
    Join Date
    Mar 2005
    Posts
    20
    OK, I think I have it figured out now. Here is what I have now. I still have some things to work on, but overall, it's doing what I need it to do. Any suggestions are appreciated.

    Thanks,
    Eric

    Code:
    public class TestTemp
    {
    //Two parameters, a temperature value (a floating-point number) 
    //and a character for the scale, either 'C' for Celsius or 'F'
    //for Fahrenheit.
    	private double tempValue;	//in degrees
    	private char tempScale;		//in either 'C' or 'F'	
    
    		
    	//----------------------------------------------------------------------
    	public void writeOutput()
    	{
    	System.out.println("The temperature is " + (tempValue) + " degrees " + tempScale + ".");
    	}
    
    	//----------------------------------------------------------------------		
    	//Four constructor methods, one for each instance variable, 
    	//(assume zero degrees if no value isspecified and Celsius
    	// if no scale is specified), one with two parameters for the
    	//two instance variables, and a default constructor (set to
    	//zero degreees Celsius.
    
    	//----------------------------------------------------------------------
    	//constructor method for the instance variable tempValue
    	public TestTemp(double initialTempValue)
    	{
    		tempScale = 'C';
    		round();
    		tempValue = initialTempValue;
    	}
    	
    	//----------------------------------------------------------------------
    	//constructor method for the instance variable tempScale
    	public TestTemp(char initialTempScale)
    	{
    		tempValue = 0;
    		initialTempScale = Character.toUpperCase(initialTempScale);
    		if(initialTempScale == 'C' || initialTempScale == 'F')
    		{
    			tempScale = initialTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			//This should take the user to...?
    			
    		}
    	}
    	
    	//----------------------------------------------------------------------
    	//constructor method for both instance variables tempValue and tempScale
    	public TestTemp(double initialTempValue, char initialTempScale)
    	{
    		round();
    		tempValue = initialTempValue;
    		initialTempScale = Character.toUpperCase(initialTempScale);
    		if(initialTempScale == 'C' || initialTempScale == 'F')
    		{
    			tempScale = initialTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			//This should take the user to...?
    		}
    	}
    	
    	//----------------------------------------------------------------------		
    	//default constructor method
    	public TestTemp()
    	{
    		tempValue = 0.0;
    		tempScale = 'C';	
    	}		
    
    	//----------------------------------------------------------------------
    	//Two accessor (get) methods, one to return the degrees Celsius,
    	//and one to return the degrees Fahrenheit.
    	//Round to the nearest tenth of a degree.
    	
    	//accessor method to return the degrees Fahrenheit.
    	public double getF()
    	{
    		if(tempScale == 'F')
    		{
    			return tempScale;
    		}
    		else
    		{
    			double tempF;
    			tempF = ((9 * tempValue)/5 + 32);  //tempF = ((9*tempC)/5 + 32)
    			tempValue = tempF;
    			tempScale = 'F';
    			round();
    			return tempF;		
    		}		
    	}
    	
    	//accessor method to return the degrees Celsius
    	public double getC()
    	{	
    		if(tempScale == 'C')
    		{
    			return tempScale;
    		}
    		else
    		{
    			double tempC;
    			tempC = (5 * (tempValue - 32)/9);			//tempC = 5*(tempF - 32)/9
    			tempValue = tempC;
    			tempScale = 'C';
    			round();
    			return tempC;	
    		}	
    	}
    	
    	//------------------------------------------------------------------------
    	//round method returns the tempValue rounded to tenths
    	public void round()
    	{
    		tempValue = Math.round(tempValue * 10.0)/10.0;
    	}
    	
    	//----------------------------------------------------------------------
    	//Three reset methods, one to reset the value, one to reset the 
    	//scale ('F' or 'C'), and one to reset both the value and the scale.
    
    	//----------------------------------------------------------------------
    	//reset method to reset tempValue
    	public void set(double newTempValue)
    	{	
    		round();
    		tempValue = newTempValue;
    		//tempScale is unchanged
    	}
    	
    	//----------------------------------------------------------------------
    	//reset method to reset tempScale
    	public void set(char newTempScale)
    	{
    		newTempScale = Character.toUpperCase(newTempScale);
    		if(newTempScale == 'C' || newTempScale == 'F')
    		{
    			tempScale = newTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			//This should take the user to...?
    		}
    		//tempValue is unchanged
    	}
    	
    	//----------------------------------------------------------------------
    	//reset method to reset tempValue and tempScale
    	public void set(double newTempValue, char newTempScale)
    	{
    		round();
    		tempValue = newTempValue;
    		newTempScale = Character.toUpperCase(newTempScale);
    		if(newTempScale == 'C' || newTempScale == 'F')
    		{
    			tempScale = newTempScale;
    		}
    		else
    		{
    			System.out.println("Error:  Must be C or F.");
    			//This should take the user to...?
    		}
    		//tempValue and tempScale are reset
    	}
    	
    	//---------------------------------------------------------------------
    	//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.
    	
    	//----------------------------------------------------------------------
    	//comparison method to test whether two temperatures are equal.
    	public boolean equals(TestTemp otherTemp)
    	{	 
    		return(this.tempValue == (otherTemp.getC()));
    	}
    	
    	//----------------------------------------------------------------------
    	//comparison method to test whether one temperatures is greater than another.
    	public boolean greaterThan(TestTemp otherTemp)
    	{
    		return(this.tempValue > (otherTemp.getC()));
    	}
    	
    	//----------------------------------------------------------------------
    	//comparison method to test whether one temperature is less than another.
    	public boolean lessThan(TestTemp otherTemp)
    	{
    		return(this.tempValue < (otherTemp.getC()));
    	}
    		
    }//end of TestTemp class	
    
    
    //-------------------------------------------------------------------------	
    //Driver program that tests all the methods.
    //Use each one of the constructors.
    //Include at least one true and one false
    //case for each of the comparison methods.
    //Test the following:  
    //		0.0 degrees C = 32 degrees F
    //		-40 degrees C = -40 degrees F
    //		100 degrees C = 212 degrees F	
    
    public class TestTempDriver
    {
    	public static void main(String[] args)
    	{
    		
    		//t8 tests the getF accessor method
    		TestTemp t8 = new TestTemp();	
    		double convertTemp = 88.888;
    		char convertScale = 'c';
    		t8.set(convertTemp, convertScale);
    		t8.getF();	
    		t8.writeOutput();
    		
    		//t9 tests the getC accessor method
    		TestTemp t9 = new TestTemp();
    		convertTemp = 99.999;
    		convertScale = 'f';
    		t9.set(convertTemp, convertScale);
    		t9.getC();	
    		t9.writeOutput();
    		
    		//t10 and t11 test the equals method to show equality
    		TestTemp t10 = new TestTemp(0.0, 'c');
    		TestTemp t11 = new TestTemp(32.0, 'f');
    		if(t10.equals(t11))
    	 	{
    			System.out.println("0.0 degrees C is equal to 32.0 degrees F.");
    		}
    		else
    		{
    			System.out.println("0.0 degrees C is not equal to 32.0 degrees F.");
    		}
    		
    		//t12 and t13 test the equals method to show equality
    		TestTemp t12 = new TestTemp(-40.0, 'c');
    		TestTemp t13 = new TestTemp(-40.0, 'f');
    		if(t12.equals(t13))
    	 	{
    			System.out.println("-40.0 degrees C is equal to -40.0 degrees F.");
    		}
    		else
    		{
    			System.out.println("-40.0 degrees C is not equal to -40.0 degrees F.");
    		}
    		
    		//t14 and t15 test the equals method to show equality
    		TestTemp t14 = new TestTemp(100.0, 'c');
    		TestTemp t15 = new TestTemp(212.0, 'f');
    		if(t14.equals(t15))
    	 	{
    			System.out.println("100.0 degrees C is equal to 212.0 degrees F.");
    		}
    		else
    		{
    			System.out.println("100.0 degrees C is not equal to 212.0 degrees F.");
    		}
    		
    		//t16 and t17 test the equals method to show inequality
    		TestTemp t16 = new TestTemp(0.0, 'c');
    		TestTemp t17 = new TestTemp(35.0, 'f');		
    		if(t16.equals(t17))
    	 	{
    			System.out.println("0.0 degrees C is equal to 35 degrees F.");
    		}
    		else
    		{
    			System.out.println("0.0 degrees C is not equal to 35 degrees F.");
    		}
    		
    		//t18 and t19 test the lessThan method to show less than		
    		TestTemp t18 = new TestTemp(18.5, 'c');
    		TestTemp t19 = new TestTemp(137.9, 'f');
    		if(t18.lessThan(t19))
    		{
    			System.out.println("18.5 degrees C is less than 137.9 degrees F.");
    		}
    		else
    		{
    			System.out.println("18.5 degrees C is not less than 137.9 degrees F.");
    		}
    		
    		//t20 and t21 test the lessThan method to show not less than
    		TestTemp t20 = new TestTemp(35.0, 'c');
    		TestTemp t21 = new TestTemp(85.9, 'f');
    		if(t20.lessThan(t21))
    		{
    			System.out.println("35.0 degrees C is less than 85.9 degrees F.");
    		}
    		else
    		{
    			System.out.println("35.0 degrees C is not less than 85.9 degrees F.");
    		}
    		
    		//t22 and t23 test the greaterThan method to show greater than
    		TestTemp t22 = new TestTemp(37.4, 'c');
    		TestTemp t23 = new TestTemp(89.5, 'f');
    		if(t22.greaterThan(t23))
    		{
    			System.out.println("37.4 degrees C is greater than 89.5 degrees F.");
    		}
    		else
    		{
    			System.out.println("37.4 degrees C is not greater than 89.5 degrees F.");
    		}
    		
    		//t24 and t25 test the greaterThan method to show not greater than
    		TestTemp t24 = new TestTemp(18.7, 'c');
    		TestTemp t25 = new TestTemp(87.9, 'f');
    		if(t24.greaterThan(t25))
    		{
    			System.out.println("18.7 degrees C is greater than 87.9 degrees F.");
    		}
    		else
    		{
    			System.out.println("18.7 degrees C is not greater than 87.9 degrees F.");
    		}
    		System.out.println("Press Enter key to end program.");
    		String junk;
    		junk = SavitchIn.readLine();
        }
    }

  6. #6
    Join Date
    Mar 2005
    Posts
    20
    I have made much progress. I believe I have everything straighted out without any possible side effects.

    Here is one of my comparison methods:
    Code:
    //comparison method to test whether one temperatures is greater than another.
    public boolean greaterThan(Temperature t)
    {
    	if(this.tempScale == (t.tempScale))
    	{
    		return(this.tempScale == t.tempScale);	
    	}
    	else if(this.tempScale == 'C')//this is C
    	{
    		return(this.tempValue > (t.getC()));
    	}
    	else //this is F
    	{
    		return(this.tempValue > (t.getF()));
    	}
    }

    Originally, I had my driver (test) code like this:

    Code:
    //t26 and t27 test the greaterThan method to show not greater than
    Temperature t26 = new Temperature(37.4, 'c');
    Temperature t27 = new Temperature(89.5, 'f');
    if(t26.greaterThan(t27))
    {
    	System.out.println("37.4 degrees C is greater than 89.5 degrees F.");
    }
    else
    {
    	System.out.println("37.4 degrees C is not greater than 89.5 degrees F.");
    }

    I have been trying to find a better way to either write the test code or change what the first if statement returns. I am going in circles here. Can anyone lend some advice or at least try to push me in the direction I need to go? I'm all ears.

    Thanks,
    Eric

  7. #7
    Join Date
    Mar 2005
    Posts
    20
    Does anyone answer questions here?

  8. #8
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Ok, Eric. Since I feel that you mean it (learning java), I suggest that we do a little online crash course, right now. How about that?
    But there's some rules:
    1. We try to do it step by step and systematically. In what is to do next and what systematically means, you have to trust me (or sjalle, if he wants to participate).
    2. You try to answer questions as honestly and as accurate and concise as possible.
    (that also means not to post thousands of lines of code)
    3. You don't feel pissed about me giving these rules (and anything else I say) ;-)
    4. We neither touch any 1.5 stuff nor exceptions but:
    - we'll have a look at Comparable
    - you're gonna implement toString()

    If that sounds ok to you, we can start with the most important question of all:
    When is your homework due?
    ;-)

  9. #9
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Ah, I forgot:
    - toString() will help you save a lot of typing you're already doing in your test code and thus make your code easier to understand.
    - implementing Comparable will concentrate all comparison code in one place and
    thus make your code easier to understand. It will also help you to understand the
    problem with your equals(), that still exists as far as I can tell.
    - constants are definitely not difficult to understand and will make your code easier to understand PLUS will make it easier to later extend functionality. I can tell you,
    teachers LOVE to come up later with such.
    - what is missing right now is an idea how to elegantly do the conversion stuff (and keep it in one place). When finished, you will have understood why the assignment as it seems to have been given to you is somewhat misleading but maybe just in being so is all the more suitable for learning.

    However, I'm gonna leave the computer now and check back tomorrow.
    CU
    Last edited by meisl; 03-07-2005 at 10:46 PM.

  10. #10
    Join Date
    Mar 2005
    Posts
    20
    Let's do it.

    When is your homework due?
    The homework was due on Sunday, March 6. Right now, it is Tuesday Morning 7:35am (I'm on Guam).

    Eric

  11. #11
    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

  12. #12
    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 10:56 PM.

  13. #13
    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

  14. #14
    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 09:34 AM.

  15. #15
    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.

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