gpt4 book ai didi

java - 为温度转换器创建构造函数

转载 作者:行者123 更新时间:2023-12-01 09:56:27 25 4
gpt4 key购买 nike

编写一个 Temperature 类,以摄氏度和华氏度表示温度,使用 float 表示温度并使用字符表示刻度:“C”表示摄氏度或“F”对于华氏度。该类应该有

四个构造函数:

  • 1 表示度数,
  • 一个用于秤,
  • 一个表示度数和比例,并且
  • 默认构造函数。

对于每个构造函数,如果未指定值,则假定为 0 度;如果未给出比例,则假定为摄氏度。”

嘿,我是一名业余java程序员...我被要求做上述声明,我对构造函数不太熟悉,但我对任何知识持开放态度:)显然我不是在要求某人给我问题的答案,但也许有人可以给我一些关于如何开始的建议...这是我到目前为止所做的:

public class TemperatureApparatus {

public class temperature{
private float c;
private float F;

public temperature(){

}
public temperature(){

}
public temperature(){

}
public temperature(){

}
}

public static void main(String[] args) {

}
}

最佳答案

Four constructors: one for the number of degrees, one for the scale, one for both the degrees and the scale, and a default constructor.

这些是您的构造函数参数。参数通过方法括号内列出的参数传递到构造函数和方法中。

构造函数的格式正确。它本质上是一个与类具有相同名称且没有返回类型的方法。现在您需要添加参数。

默认构造函数没有参数:

public Temperature() { //Class names should be capitalized!
//Default constructors often do nothing, but you can set default values here if you want
}

这是仅获取度数的构造函数的签名:

public Temperature(float degrees) {
//Assign the "degrees" argument to an instance variable here
//You might consider assigning a value to a "scale" variable by default as well
}

此赋值可能需要您填写该构造函数的主体,因此将给定值赋给 float在类里。现在为其他所需的参数创建构造函数。由于作业需要“F”或“C”作为等级,因此您可以安全地使用 char作为该数据的参数。

完成作业后,您可能会考虑挑战自己:假设用户现在可以拥有 Temperature带有 float 的对象学位和a char规模,您如何实现 getTemperature()方法?

哦,你没有理由像现在这样嵌套类。放Temperature在与运行 main 的类分开的类中如果您需要做出可运行的答案。

关于java - 为温度转换器创建构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com