我正在尝试创建一个具有单个构造函数的类,该构造函数接受温度(以摄氏度为单位)作为double,如果温度小于-273.15,则将其设置为-273.15。它还计算不同测量单位的其他温度,但这并不重要。出于某种原因,我得到的逻辑错误不能纠正小于-273.15到-273.15的输入。
public class TemperatureC
{
private double temperature;
public TemperatureC(double c)
{
if (temperature < -273.15)
{
temperature = -273.15;
}
else
{
temperature = c;
}
}
public TemperatureC()
{
temperature = -273.15;
}
public double getC()
{
return temperature;
}
public double getF()
{
return ((temperature * 1.8) + 32);
}
public double getK()
{
return (temperature + 273.15);
}
public void setC(double c)
{
if (temperature >= -273.15)
{
temperature = c;
}
}
}
这就是使用该课程的内容。
import java.util.Scanner;
public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();
System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);
System.out.println("The current temperature in Celsius is:" + temp.getC());
System.out.println("The current temperature in Fahrenheit is:" + temp.getF());
System.out.println("The current temperature in Kelvin is:" + temp.getK());
System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);
System.out.println("The current temperature in Celsius is:"+ temp.getC());
System.out.println("The current temperature in Fahrenheit is:"+ temp.getF());
System.out.println("The current temperature in Kelvin is:"+ temp.getK());
}
}
这是我错误的输出:
Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
它应该纠正小于-273.15到-273.15的输入。
答案 0 :(得分:1)
您的问题是您正在检查构造函数的默认值。首先将温度设置为c或检查c。
public TemperatureC(double c)
{
temperature = c;
if (temperature < -273.15)
{
temperature = -273.15;
}
应该有效,作为副作用,不再需要其他
答案 1 :(得分:0)
你只是在检查温带&lt; -273.15在构造函数中,所以每当你调用setC然后你就不会纠正它。此外,在setC方法中,除非达到或高于-273.15
,否则不要设置温度你可以完全删除构造函数,因为你还没有调用它并更改setC中的逻辑以检查温度&lt; -273.15