【问题标题】:Difficulty with a loop in the main that makes a calls to a method (Temperature Conversions)调用方法的主循环有困难(温度转换)
【发布时间】:2018-02-25 16:51:12
【问题描述】:

我正在尝试编写一个接收华氏温度并返回等效摄氏温度的方法。为此,我的任务是在 main 中编写一个循环,该循环调用一个方法并打印华氏值的转换:0、5、10、15、...、100。

这是我所拥有的:

import java.util.Scanner;

public class TemperatureConverter {

    public static void main(String[] args) {
        int F;
        F = 0;
        double tempCelsius;

        while (F <= 100) {
            convert(F);
            System.out.println(F + " degrees F corresponds to " + tempCelsius + " degrees C");
            F = F + 5;
        }
    }

    public static double convert(int F) {
        tempCelsius = ((5.0 / 9.0) * (F - 32));

        return tempCelsius;
    }
}

我得到的错误是

/TemperatureConverter.java:32:错误:找不到符号
温度摄氏度 = ((5.0 / 9.0) * (F - 32));
^

我很欣赏任何方向。

【问题讨论】:

  • 你知道变量作用域吗?如果在方法中声明局部变量,则不能从其他方法访问它。您应该删除convert() 中的临时分配,而使用tempCelsius = convert(F); 中的返回值。附带说明一下,Java 有一个方便的 += 运算符; F = F + 5 可以写成F += 5;

标签: java loops methods


【解决方案1】:

你的函数应该是

public static double convert(int F) {
    return ((5.0 / 9.0) * ( F - 32 ));
}

你应该通过以下方式调用它:

tempCelsius = convert(F);

之前您尝试从convert 访问局部变量tempCelsius,但该变量仅在main 中可用。

【讨论】:

    【解决方案2】:

    您在 main 方法中声明了变量 tempCelsius,因此 convert 方法不知道它。 有两种解决方案:

    1. 在 main 方法之外声明 tempCelsius。

    1. 在转换方法中不要使用 tempCelsius 变量,而是直接返回计算值。 eg.return(华氏转摄氏的逻辑)

    【讨论】:

      【解决方案3】:

      main 方法中的声明 double tempCelsius; 在 convert 方法中没有有效范围。所以你也必须在 convert 方法中再次声明它。一旦你这样做了,你必须将从 convert 方法返回的值存储到 main 方法中的 tempCelsius 变量中以便打印它。简单来说就是 tempCelsius您在 main 方法中声明的与 convert 方法中的 tempCelsius 无关,因为它们的作用域不同。

      【讨论】:

        【解决方案4】:

        在while循环中更新下面的语句并查看它运行

        这个

        convert(F);
        

        与:

        tempCelsius = convert(F);
        

        【讨论】:

          猜你喜欢
          • 2020-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-25
          • 2015-07-03
          • 1970-01-01
          • 1970-01-01
          • 2012-08-25
          相关资源
          最近更新 更多