【问题标题】:Error: celsius cannot be resolved to a variable错误:摄氏度无法解析为变量
【发布时间】:2011-10-12 00:05:05
【问题描述】:

以下代码出错:

import java.util.Scanner;
public class FahrenheitToCelsius{


 public static void main(String[]args){
    convertFToC();
 }

  /*gets input representing fahrenheit and displays celsius equivalent*/
  public static void convertFToC(){
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter Fahrenheit temperature");
    double fahrenheit = scan.nextInt();            
    System.out.println(fahrenheit + " degrees Fahrenheit is " +
      fMethod(celsius) + " degrees Celsius");
  }


  /* calculates and returns the celsius equivalent */
  public static double toCelsius(double fahr){
    int BASE = 32;
    double CONVERSION_FACTOR = 9.0/ 5.0;
    double celsius = ((fahr-BASE)/(CONVERSION_FACTOR));
    return celsius;
  }
}

我得到以下信息:

Error: celsius cannot be resolved to a variable

我需要使用fMethod 来调用System.out.println 中的toCelsius,但是我不断收到此错误。

【问题讨论】:

  • 摄氏度无法解析为变量在哪里?

标签: java variables methods


【解决方案1】:

你根本没有显示fMethod,但看起来你只是想要:

System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit)
                   + " degrees Celsius");

您不能在main 中使用celsius,因为它是toCelsius 方法中的局部变量。相反,您需要调用该方法并使用返回值。

【讨论】:

  • @Bohemian:我会支持的。 Jon Skeet - 互联网上最快的手指。
【解决方案2】:

你需要调用你的toCelsius(double fahr)方法,像这样:

System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit) + " degrees Celsius"); // Step 4

【讨论】:

    【解决方案3】:
    System.out.println(fahrenheit + " degrees Fahrenheit is " + fMethod(celsius) + " degrees Celsius"); //Step 4
    

    应该读

    System.out.println(fahrenheit + " degrees Fahrenheit is " + toCelsius(fahrenheit) + " degrees Celsius"); //Step 4
    

    【讨论】:

    • @Ron_ish - 尽管我很感激接受,但我认为这是 Jon 的正确答案 - 他得到了相同的答案,并且首先得到了答案(并不是他实际上需要代表!)
    【解决方案4】:

    在标记为 step4 的行上,您有一个名为 celsius 的未声明变量。应该是fahrenheit吧?

    【讨论】:

      【解决方案5】:

      在方法convertFToC()

      您从用户那里获得fahrenheit 并调用fMethod(celsius) 你应该打电话给fMethod(farenheit)

      更重要的是:

      如果您阅读编译器错误消息,您不仅会收到错误信息,还会收到文件名和行号。如果您转到行号,您会突然看到一个 celcius 变量。

      这很容易。我知道问 SO 更容易,但你永远不会学会阅读错误消息并以这种方式解决问题。

      学习阅读和理解错误消息。他们在那里是有原因的。

      【讨论】:

      • [line: 16] 错误:方法 fMethod(double) 未定义为 FahrenheitToCelsius 类型
      【解决方案6】:

      你在这里使用摄氏度:

      System.out.println(fahrenheit + " degrees Fahrenheit is " + fMethod(celsius) + " degrees Celsius");
      

      但是,您确实只在 toCelsius 中声明了摄氏度,这超出了范围。

      【讨论】:

        【解决方案7】:

        当我认为您的意思是 fahrenheit 时,您调用不存在的 fMethod 并传递 celsius 的值。

        变量celsiustoCelsius() 的局部变量,因此在convertFToC() 内部是不可解析的。

        【讨论】:

          猜你喜欢
          • 2015-12-21
          • 1970-01-01
          • 2012-11-20
          • 2013-07-02
          • 2014-08-09
          • 2014-09-01
          • 2015-01-31
          • 1970-01-01
          • 2019-06-18
          相关资源
          最近更新 更多