这是一个合法的 if 句子吗?
Is this a legal if sentance?
我刚开始编码,无法让这个 "Heater" 对象工作。它只是在尝试给 temp 一个更高的值时提示 if else 语句 "its too hot" 并且在调用 "colder" 方法时它不会停止/低于最小温度值。谢谢
public class Heater {
private double temp;
private double min;
private double max;
private double increment;
public Heater(double min, double max) {
temp = 15;
increment = 5;
}
public void Warmer() {
if(temp + increment <= max) {
temp = temp + increment;
} else if(temp + increment > max) {
System.out.println("Too hot");
}
}
public void Colder() {
if(temp - increment >= min){
temp = temp - increment;
} else if (temp - increment < min){
System.out.println("Too cold");
}
}
public double getTemp() {
return temp;
}
}
您没有在构造函数中设置 min
和 max
,因此默认情况下它们保持为 0。试试这个:
public Heater(double min, double max) {
this.min = min;
this.max = max;
temp = 15;
increment = 5;
}
- 您正在为方法名称使用大写字母。大写适用于 Class 个名字。
- 您没有设置
min
。它的值为零。
- 您不需要
else if
条件 - 只需使用 else
即可。
public void colder() { // method name, make lower case.
if(temp - increment >= min){
temp = temp - increment;
} else {
System.out.println("Too cold");
}
}
我刚开始编码,无法让这个 "Heater" 对象工作。它只是在尝试给 temp 一个更高的值时提示 if else 语句 "its too hot" 并且在调用 "colder" 方法时它不会停止/低于最小温度值。谢谢
public class Heater {
private double temp;
private double min;
private double max;
private double increment;
public Heater(double min, double max) {
temp = 15;
increment = 5;
}
public void Warmer() {
if(temp + increment <= max) {
temp = temp + increment;
} else if(temp + increment > max) {
System.out.println("Too hot");
}
}
public void Colder() {
if(temp - increment >= min){
temp = temp - increment;
} else if (temp - increment < min){
System.out.println("Too cold");
}
}
public double getTemp() {
return temp;
}
}
您没有在构造函数中设置 min
和 max
,因此默认情况下它们保持为 0。试试这个:
public Heater(double min, double max) {
this.min = min;
this.max = max;
temp = 15;
increment = 5;
}
- 您正在为方法名称使用大写字母。大写适用于 Class 个名字。
- 您没有设置
min
。它的值为零。 - 您不需要
else if
条件 - 只需使用else
即可。
public void colder() { // method name, make lower case.
if(temp - increment >= min){
temp = temp - increment;
} else {
System.out.println("Too cold");
}
}