Okay so I've been trying to figure this out for about 4 hours now and cannot figure out how to make these two methods work correctly. My instructor told me he wanted this for the two methods.Write an equals method that returns true if two Temperature objects are within 1/10 of a degree of each other.
Write a compareTo method that returns -1 if the invoking object has a lower temp, 0 if they are the same, and 1 if the invoking object is larger.
Here is my code
Code:public class Temperature { private double degrees; private char scale; public Temperature() { this(0,'C'); } public Temperature(double degrees) { this.scale = 'C'; } public Temperature(char scale) { this.degrees = 0; } public Temperature(double degrees, char scale) { this.degrees = degrees; this.scale=scale; } public void setScale(char scale) { this.scale=scale; } public char getScale() { return scale; } public void setDegrees(double degrees) { this.degrees=degrees; } public double getDegrees() { return degrees; } public double getC() { if(this.scale == 'C') { return degrees; } else { return (5*(degrees-32))/9; } } public double getF() { if(this.scale == 'F') { return degrees; } else { return (9*(degrees)/5)+32; } } // public boolean equals(Object obj ) // { // if(!(obj instanceof Temperature)) // { // return false; // } // Temperature other = (Temperature)obj; // return this.degrees.equals(other.degrees); // } public int compareTo(Temperature other) { if(this.getF()< this.getF() || this.getC() < this.getC()) { return -1; } if(this.getF()> this.getF() || this.getC() > this.getC()) { return 1; } return 0; } public String toString() { return "Value in Farenheit " + this.getF() + "\n" + "Value in Celcius " + this.getC(); } }
And here is the TestTemperature that he gave us.
Could anyone help me? I'm just really lost as to how to figure this out.Code:public class TestTemperature { public static void main(String[] args) { // degrees = 0 scale = C Temperature temp1 = new Temperature(); // degrees = 80 scale = C Temperature temp2 = new Temperature(80); // degrees = 0 scale = F Temperature temp3 = new Temperature('F'); // degrees = 32 scale = F Temperature temp4 = new Temperature(32, 'F'); System.out.println("Temp4 in C is: " + temp1.getC()); System.out.println("Temp4 in F is: " + temp1.getF()); // should be same if(temp1.equals(temp4)) { System.out.println("same"); } else { System.out.println("not same"); } // to string showing both scales System.out.println(temp4); // will print -1, 1, 0 System.out.println(temp1.compareTo(temp2)); System.out.println(temp2.compareTo(temp1)); System.out.println(temp1.compareTo(temp4)); } }




Reply With Quote