【发布时间】:2017-10-15 21:23:11
【问题描述】:
当我编译代码时,它告诉我有 2 个错误,这两个变量可能都没有被初始化错误。变量摄氏度和华氏度是问题所在。我相信我已经用它们各自的方法初始化了它们。
import java.io.*;
class Converter
{
double celsius,fahrenheit,temperature,inFahrenheit,inCelsius;
double Celsius (double temperature)
{
celsius = (5.0 / 9.0) * (temperature - 32);
return celsius;
}
double Fahrenheit (double temperature)
{
fahrenheit = (9.0 / 5.0) * temperature + 32;
return fahrenheit;
}
}
public class ConverterTester
{
public static void main(String[] args)throws IOException
{
double temperature,fahrenheit,celsius;
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader (inStream);
String intemperature,inCelciusOrFahrenheit;
System.out.println("What is the temperature");
intemperature = stdin.readLine();
temperature = Double.parseDouble(intemperature);
System.out.println("What is the temperature you wish to convert to, Celsius or Fahrenheit");
inCelciusOrFahrenheit = stdin.readLine();
if (inCelciusOrFahrenheit.equals("Celsius"))
{
Converter Conversion1 = new Converter();
Conversion1.Celsius(celsius);
System.out.println("Your new temperature is " + celsius);
}
else if(inCelciusOrFahrenheit.equals("Fahrenheit"))
{
Converter Conversion2 = new Converter();
Conversion2.Fahrenheit(fahrenheit);
System.out.println("Your new temperature is " + fahrenheit);
}
else
{
System.out.println("Please enter a correct temperature");
System.exit(0);
}
}
}
调用Celsius方法和Fahrenheit方法时出现错误,我不确定调用方法时是否允许使用变量。但是,我找不到任何说这是不允许的。
【问题讨论】:
-
celcius和fahrenheit都不会被赋值。 -
而你从不使用
temperature -
你在哪里初始化
celcius或fahrenheit? -
为什么你认为相同的变量名意味着它们完全相同相同?你的逻辑甚至没有意义。这个方法在这里调用:例如
Conversion1.Celsius(celsius)。该未初始化的变量作为temperature传递到Celsius,您假设您使用来自ConverterTester的变量初始化相同的celsius变量。因此,您需要一个未初始化的变量来初始化自己? -
您即将遇到的另一个问题:stackoverflow.com/questions/513832/…
标签: java methods compiler-errors