java - 如何在方法内调用方法

标签 java methods

虽然这可能非常简单,但我遇到了麻烦。

我必须创建一个华氏温度到摄氏度、摄氏温度到华氏温度的转换器。此后的任务是:

在main方法中声明一个double类型的变量 并将其初始化为一个值。 3. 在 main 中添加一行,调用 fToC 方法并将步骤 2 中声明的变量作为其参数传递。

我知道也要声明一个变量并将其设置为一个数字,我必须这样做:

double var = 0;

但是我不知道如何调用this中的方法。

我尝试调用该方法,但它似乎格式不正确,而且我找不到如何正确执行它(Google 搜索了很多:( )

import java.util.Scanner;

public class ExerciseOne {
    public static void main( String[] args ) {

        int choice;
        double variable = 0;

        public static float ftoC(double var) {    //This line is giving me trouble

            System.out.println( "What would you like to do? \n \n 1 - Fahnrenheit to Celsius \n 2 - Celsius to Fahrenheit \n 3 - Quit" );
            Scanner dylan = new Scanner(System.in);
            choice = dylan.nextInt();

            if (choice == 1)
            {
                System.out.println( "What number do you want to convert to Celsius?" );
                float input = dylan.nextFloat();
                float output = ftoC(input);
                System.out.println( input + " degrees Fahrenheit is " +
                    ftoC(input) + " degrees Celsius." );
            }

            if (choice == 2)
            {
                System.out.println( "What number do you want to convert to Fahrenheit?" );
                float input = dylan.nextFloat();
                float output = ctoF(input);
                System.out.println( input + " degrees Celsius is " +
                    ctoF(input) + " degrees Fahrenheit." );
            }

            if (choice == 3)
            {
                System.out.println( "Exiting application.");
            }
        }
    }

    public static float ftoC(float f)
    {
        float celsius = (f-32)*(5f/9f);
        return celsius;
    }

    public static float ctoF(float c)
    {
        float fahrenheit = c*9/5 + 32;
        return fahrenheit;
    }
}

最佳答案

要调用 ftoC 方法,请使用以下语法:

ftoC(x); // Assuming x is the name of the float you created.

注意:我在您的示例中注意到的一件事是,您将要传入的值声明为 double variable = 0; ,但您的方法需要一个 float。如果将 double 传递给需要 float 的方法,那么它将无法编译。您需要将double变量更改为float变量

注意注意:还有一件事。您应该适本地命名变量。即使将其称为也比将其称为变量更好。 变量这个名字并没有告诉读者它的用途。

注意 x 3:我注意到的另一件事是,您将变量设置为值0,但问题指定:

In the main method declare a variable of type double and initialize it to a value. 3.

因此,您应该考虑将 0 替换为明显明显的内容。

关于java - 如何在方法内调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21993438/

相关文章:

java - 如何在 Clojure 中实现具有具体类型参数的接口(interface)?

ruby - 更改方法中传递的变量

ruby-on-rails - 替换 Ruby on Rails 3.1 中的 'auto_link' 方法

java - 在泛型类中实现数组列表的 Add 方法

java - 引用构造函数而不重置参数值?

C# - 如何使用数组数组作为 "parameterized"方法的输入?

java - 重复使用 Selenium 元素定位器的最佳方法是什么?

java - 如何修复 JVM 中的单例问题?

java - SecurityFilterChain Bean 不保护应用程序

java - 检查 Java 中的两个参数,要么都不为空,要么都优雅地为空