有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中使用对象的温度转换

因此,我目前正在编写一个程序,使用的对象是用户输入初始温度,然后程序必须将其计算为摄氏度,这只是用户输入,然后是华氏度,然后是开尔文。该类还有一个构造函数,它接受作为双参数提供的初始温度。如果此参数为< -273.15,请将其设置为-273.15。我认为我的思路是正确的,但当我编译它时,它并没有做我想要的,关于如何修复它的任何提示

有了这段代码,输出给我

Please enter the initial temperature: 20
The current temperature in Celsius is: 0.0
The current temperature in Fahrenheit is: 32.0
The current temperature in Kelvin is: 273.15

这是不对的。。。有什么建议吗

//blueprint
public class TemperatureC{
    private double temperatureC;

    public TemperatureC(){
        if(temperatureC<-273.15){
            temperatureC = -273.15;}
        else{}
    }

    public void setC(double c){
        temperatureC = c;
    }
    public double getC(){return temperatureC;}
    public double getF(){return (temperatureC * 1.8) + 32;}
    public double getK(){return temperatureC + 273.15;}
}   



//code
import java.util.Scanner;

public class TemperatureTester{
    public static void main(String[] args){

        TemperatureC temp = new TemperatureC();

        double initialTemperature;
        double celsius=temp.getC();
        double fahrenheit=temp.getF();
        double kelvin=temp.getK();

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Please enter the initial temperature: ");
        initialTemperature = keyboard.nextDouble();


        //TemperatureC temp = new TemperatureC();

        System.out.println("The current temperature in Celsius is: " + celsius);
        System.out.println("The current temperature in Fahrenheit is: "+fahrenheit);
        System.out.println("The current temperature in Kelvin is: "+kelvin);    
    }   
}

共 (1) 个答案

  1. # 1 楼答案

    在知道celsiusfahrenheitkelvin的值之前,您正在分配这些值。你想让你的测试人员看起来更像这样吗

    public static void main(String[] args) {
      TemperatureC temp = new TemperatureC();
      double initialTemperature;
      Scanner keyboard = new Scanner(System.in);
      initialTemperature = keyboard.nextDouble();
      temp.setC(initialTemperature);
    
      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());
    }
    

    因此,这些操作现在是在initialTemperature的温度被设置之后完成的