温度转换方法输出 Java

Temperature Conversion Method Outputting Java

我必须写一个 class 称为温度,我唯一的问题是当我尝试调用转换方法时。每当我运行主程序,转换输出是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 , 浮动, 双...).

编辑:我在您的代码中发现了另一个问题:

 (this.temp - 32) * (double)(5/9);

5和9是整数,除法结果为0。需要将其中一个操作数转换为double,在/操作之前:

 (this.temp - 32) * ((double)5/9);

或:

(this.temp - 32) * (5./9.);

你的问题不是变量的初始化吗?当您使用 this.temp 时,您正在访问转换方法中的 "zero" 而不是外部值。实际上在这种情况下你不需要使用这个。

对不起,如果我错了

我发现您的代码有两个问题。

1) 字符串相等:java 中的字符串相等使用等号而不是==。它们在 java 中完全不同,仅用于原始数据类型相等。

2) 您需要创建一个public 方法来设置比例。您没有在任何地方设置比例值

public void setScale (String scale){ 
this.scale=scale;
}

and your getter should be changed to

public String getScale() {
    return scale;
}