java中怎么引用自己写的函数

我是一个java新手,写了一段代码,有关:摄氏度和华氏度之间的互相转化

package method;

import method.HuaShe;
public class TestCToFandFToC {
public static void main(String[] args){
System.out.println("摄氏 华氏 华氏 摄氏");
for(int i = 1;i <= 10;i++){
double she1 = 40.0;
double hua1 = cToF(she1);
double hua2 = 120.0;
double she2 = fToC(hua2);
System.out.println(she1 + " " + hua1 + " " + hua2 + " " + she2);
she1 -= 1;
hua2 -= 10;
}
}
}

//问题:为何出现错误?我import了啊!!

其中cToF和fToC是我另外写的函数,但是没有和上面代码段放在一起,而是新建了一个:

 package method;

public class HuaShe {
    static double cToF(double c){
        double ft = (9.0 / 5) * c + 32;
        double f = (int)(ft * 100) / 100.0;
        return f;
    }
//--------------------------------------
    static double fToC(double f){
        double ct = (f - 32) / (9.0 / 5);
        double c = (int)(ct * 100) / 100.0;
        return c;
    }
}

然后运行主函数时
cToF(she1);和fToC(hua2);报错:
The method cToF(double) is undefined for the type TestCToFandFToC
为什么会这样???
谢谢!


宝慕林4294392
浏览 1061回答 7
7回答

qq_花开花谢_0

TestCToFandFToC 类中没办法直接调用 cToF(she1)和fToC(hua2)这两个方法,不管你是不是import如果需要使用,可以&nbsp;HuaShe&nbsp;test&nbsp;=&nbsp;new&nbsp;HuaShe&nbsp;(); &nbsp;double&nbsp;hua1&nbsp;=&nbsp;test.cToF(she1);,也可以&nbsp;double&nbsp;hua1&nbsp;=&nbsp;HuaShe.cToF(she1);还可以import时,&nbsp;static&nbsp;import&nbsp;method.HuaShe

白猪掌柜的

你定义的HuaShe类里面的方法是静态的,要么通过HuaShe.cToF调用,要么请把static去掉。

米琪卡哇伊

用的静态方法,去掉static

暮色呼如

写成内部方法 或者静态方法

开心每一天1111

这样&nbsp;public..

守着一只汪

改成静态方法就应该好了吧
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java