我必须编写一个名为 speed 的类,我唯一的问题是当我尝试调用转换方法时。每当我运行主程序时,转换输出为 0.0
它与使用私有变量有关吗?
代码如下。
非常感谢!
public class Temperature {
private double temp;
private String scale;
public Temperature(double temp) {
this.temp = temp;
}
public String toString () {
return "your temp is " + this.temp;
}
public double getTemp() {
return this.temp;
}
public String getScale(String scale) {
this.scale = scale;
return this.scale;
}
public double conversion() {
double temp = 0;
if (this.scale == "fahrenheit") {
temp = (this.temp - 32) * (double)(5/9);
}
else if (this.scale == "celsius") {
temp = (this.temp * (double)(9/5)) + 32;
}
return temp;
}
public boolean aboveBoiling(double temp) {
if (this.scale == "fahrenheit") {
return temp >= 212;
}
else if (this.scale == "celsius") {
return temp >= 100;
}
return true;
}
}
下面是我测试函数调用的测试驱动程序
import java.util.*;
public class testdriver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Temperature userTemp;
String userScale;
//userTemp = new Temperature(1.0);
System.out.print("Please enter your temp scale(fahrenheit or celius): ");
userScale = sc.next();
System.out.println();
System.out.print("Please enter your temp in " + userScale + ": ");
userTemp = new Temperature(sc.nextDouble());
System.out.println();
System.out.println(userTemp.toString());
System.out.println();
System.out.println("your temp is: " + userTemp.getTemp());
System.out.println();
System.out.println("your scale is: " + userTemp.getScale(userScale));
System.out.println();
System.out.println(userTemp.conversion());
System.out.println();
double userTemp2 = userTemp.conversion();
System.out.println(userTemp.aboveBoiling(userTemp2));
}
}
将this.scale == "fahrenheit"
和this.scale == "celcius"
替换为this.scale.equals("fahrenheit")
和this.scale.equals("celcius").
在java中,==运算符仅比较引用或原始值(int,long,float,double...(。
编辑:我在您的代码中发现了另一个问题:
(this.temp - 32) * (double)(5/9);
5 和 9 是整数,则除法将导致 0。您需要在/操作之前将其中一个操作数转换为双精度:
(this.temp - 32) * ((double)5/9);
或:
(this.temp - 32) * (5./9.);
我看到你的代码有两个问题。
1(字符串相等:在java中使用equals而不是==表示字符串相等。它们在 java 中完全不同,仅用于原始数据类型相等。
2( 您需要创建一个公共方法来设置缩放。您没有在任何地方设置比例值
public void setScale (String scale){
this.scale=scale;
}
and your getter should be changed to
public String getScale() {
return scale;
}
你的问题不是变量的初始化吗? 当您使用 this.temp 时,您是在转换方法中使用"零"而不是外部值。实际上,在这种情况下,您不需要使用它。
对不起,如果我弄错了