我正在尝试创建一个具有单个构造函数的类,该构造函数将温度(以摄氏度为单位)接受为两倍,并且如果温度小于-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的输入。
最佳答案
您的问题是您正在检查构造函数的默认值。首先将温度设置为c或对c进行检查。
public TemperatureC(double c)
{
temperature = c;
if (temperature < -273.15)
{
temperature = -273.15;
}
应该起作用,作为副作用,不再需要其他