这是我的提示:
要创建温度转换器,我想知道newTemp
中OtherUnit
对象的返回意味着什么?
实现一个名为Temperature的类,表示华氏温度或摄氏温度。允许度数具有小数位(例如double)并使用枚举来存储单位。将枚举TemperatureUnit
命名为Celsius,Fahrenheit和Kelvin。具体来说,Temperature类具有以下实例变量(a.k.a。字段或数据):
degrees
(双)
unit
(TemperatureUnit - 来自您创建的枚举)
Temperature类将具有以下方法:
Create a new Temperature
(给定度和单位的值)[参数化构造函数]
Create a new Temperature
(没有参数 - 将温度初始化为0.0摄氏度)[默认构造函数]
Create a new Temperature
(来自另一个温度)[复制构造函数]
getDegrees
getUnit
setDegrees
setUnit
convertTo
(TemperatureUnit otherUnit) - 此方法将一个单位的度数转换为另一个单位的度数(例如华氏度到Celsuis),如果进行转换则返回true,否则返回false(转换的唯一方式)是不是单位是相同的(例如华氏温度到华氏温度)
inOtherUnit
(TemperatureUnit otherUnit) - 此方法将在otherUnit中返回一个新的Temperature对象,而不更改当前对象。
这是我已有的代码:
public class Temperature {
private double degrees;
private TempUnit unit;
public Temperature(double degrees, TempUnit unit) {
this.degrees = degrees;
this.unit = unit;
}
// default constructor
public Temperature() {
this.degrees = 0.0;
this.unit = TempUnit.Celsius;
}
public Temperature(Temperature copyTemperature) {
this.degrees = copyTemperature.degrees;
this.unit = copyTemperature.unit;
}
public double getDegrees() {
return this.degrees;
}
public TempUnit unit() {
return this.unit;
}
public void setDegrees(double newDegrees) {
this.degrees = newDegrees;
}
public boolean convertTo(TempUnit otherUnit) {
if (this.unit == otherUnit) {
return false;
}
if (this.unit == TempUnit.Celsius && otherUnit == TempUnit.Fahrenheit) {
this.degrees = this.degrees * (9.0 / 5.0) + 32.0;
} else if (this.unit == TempUnit.Celsius && otherUnit == TempUnit.Kelvin) {
this.degrees += 273.15;
} else if (this.unit == TempUnit.Fahrenheit && otherUnit == TempUnit.Celsius) {
this.degrees = (this.degrees - 32.0) * 5.0/9.0;
} else if (this.unit == TempUnit.Fahrenheit && otherUnit == TempUnit.Kelvin) {
this.degrees = (this.degrees + 459.67) * 5.0/9.0;
} else if (this.unit == TempUnit.Kelvin && otherUnit == TempUnit.Celsius) {
this.degrees = this.degrees - 273.15;
} else if (this.unit == TempUnit.Kelvin && otherUnit == TempUnit.Fahrenheit) {
this.degrees = (this.degrees * 9.0/5.0) - 459.67;
}
this.unit = otherUnit;
return true;
}
public boolean another(TempUnit otherUnit) {
if (this.unit == otherUnit) {
return false;
}
else
return true;
}
答案 0 :(得分:0)
基本上,方法otherUnit
需要返回一个不同的Temperature
对象,该对象在某个其他温度单位中具有相同的温度。 otherUnit
本质上是一个转换器,也就是说,在给定对象的当前状态的情况下,它将返回一个具有不同值但等效于当前状态的新对象。
因此,表示温度为0摄氏度的物体可以转换为另一个32华氏度的物体,而该物体又可以转换为272开尔文的物体。这意味着尽管对象具有不同的值,但考虑到上下文(即温度值和单位),它们都是等价的。
基本上,这意味着类似的事情:
public Temperature otherUnit(TempUnit unit) {
switch(unit) {
case Celcius: {
//If the current temperature is in Celcius, then return the current object.
if(this.unit == TempUnit.celcius) return this;
// return a new object which has the equivalent temperature in Celcius.
}
...
}
}