簡體   English   中英

變量可能沒有被初始化,即使它已經在方法中

[英]Variable may not of been initialized even though it has been in the method

當我編譯代碼時,它告訴我有 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);
    }
}
}       

當我調用攝氏度方法和華氏度方法時會發生錯誤,我不確定在調用這些方法時是否允許使用這些變量。 然而,我無法找到任何說這是不允許的。

您唯一的問題是您沒有初始化溫度、攝氏度或華氏度。
在此處創建變量時:
double celsius,fahrenheit,temperature,inFahrenheit,inCelsius; ,您需要使溫度等於某個值,例如 20。
我建議取出整數攝氏度和華氏度,或者將它們設置為等於攝氏和華氏度的雙倍,您設置為等於溫度......數學。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM