我正在两个单独的类中编写代码,该代码将温度作为两个单独的变量并将其打印出来,然后运行转换方法以获取其他比例的温度。我不断收到错误,无法从代码的Temperature.java 部分中的静态上下文引用非静态变量值,因为构造函数中的变量不是静态的。整个概念对我来说有点令人困惑,我希望任何关于希望静态和非静态工作以及如何在它们之间毫无问题地切换的意见。
代码如下:
public class Temperature
{
int value = 50;
String scale = "F";
public Temperature(int value, String scale){
value = value;
scale = scale;
}
public static void value(int value){
int number;
}
public static boolean scale(String scale){
if (scale == "C"){
return true;
}
else if (scale == "F"){
return true;
}
else if (scale == "K"){
return true;
}
else{
return false;
}
}
public static void convertToCelsius(int value, String scale){
if (scale == "F"){
int newValue = (5/9) * (value - 32);
System.out.println("The equivalent tempurature is " + newValue + "C");
}
else if (scale == "K"){
double newValue = value - 273.15;
System.out.println("The equivalent tempurature is " + newValue + "C");
}
else{
}
}
public static void convertToFarenheit(int Value, String scale){
if (scale == "C"){
int newValue = ((9/5) * (value + 32));
System.out.println("The equivalent tempurature is " + newValue + "F");
}
else if (scale == "K"){
int newValue = ((9/5) * (value - 273) + 32);
System.out.println("The equivalent tempurature is " + newValue + "F");
}
else{
}
}
public static void convertToKelvin(int value, String scale){
if (scale == "F"){
int newValue = ((5/9) * (value - 32) + 273);
System.out.println("The equivalent tempurature is " + newValue + "C");
}
if (scale == "C"){
double newValue = (value + 273.15);
System.out.println("The equivalent tempurature is " + newValue + "C");
}
else{
}
}
}
对于 main 方法,代码位于单独的类中,如下所示:
public class UsingTemperature
{
public static void main(String[] args)
{
Temperature t = new Temperature(50, "F");//declaring an object
System.out.println(t);
// Test out conversions:
System.out.println("Test out conversions:");
// F to C
t.convertToCelsius();
System.out.println(t);
// C to F
t.convertToFahrenheit();
System.out.println(t);
// F to K
t.convertToKelvin();
System.out.println(t);
// K to F
t.convertToFahrenheit();
System.out.println(t);
// F to K:
t.convertToKelvin();
System.out.println(t);
// K to C
t.convertToCelsius();
System.out.println(t);
// C to K
t.convertToKelvin();
System.out.println(t);
}
}
最佳答案
当您在方法中使用静态修饰符时,这些方法将独立于为该类创建的任何实例而存在。 所以在你的温度类中你的静态方法:
- 在创建新的Temperature实例之前存在
- 无论您拥有多少个Temperature 实例,静态方法都只有一份副本。
此外,我认为您只希望温度作为实用程序,因此构造函数没有任何意义,因为构造函数仅用于创建实例
当您需要使用Temperature中的方法时:Temperature.name_method(params)
关于Java:无法从静态上下文错误中引用非静态变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25044718/