方法 ____ 未定义类型 ____

The method ____ is undefined for the type ____

好吧,我有一个家庭作业,我很难调用另一个 class 中的主 class 上的方法。

基本上 "test" 方法在 landEnclosure.java class 中,我试图在我的主 class 上调用它,即 landAndEat.java

它们都在同一个包裹内:

Image

这是我尝试调用方法的主要 class:

public class landAndEat {
    public static void main(String[] args) {
        test();

    } //end class

} //end main

这是正在创建方法的 class:

import java.util.Scanner;

public class landEnclosure {
    public void test() {
        double area, ratioA = 0, ratioB = 0, x, l, w, perimeter;
        Scanner input = new Scanner(System.in);

        System.out.println("What area do you need for your enclosure in square feet?");
        area = input.nextDouble(); 

        if( area > 0 && area <= 1000000000) { //Input specification 1
            System.out.println("What is the ratio of the length to the width of your enclosure?");
                ratioA = input.nextDouble();
                ratioB = input.nextDouble();
        }
                else
                    System.out.println("It needs to be a positive number less than or equal to 1,000,000,000!");

                if(ratioA > 0 && ratioA < 100 && ratioB > 0 && ratioB < 100) { //Input specification 2
                    x = Math.sqrt(area/(ratioA*ratioB));
                    l = ratioA * x;
                    w = ratioB * x;
                    perimeter = (2 * l) + (2* w);

                    System.out.println("Your enclosure has dimensions");
                    System.out.printf("%.2f feet by %.2f feet.\n", l, w);
                    System.out.println("You will need " + perimeter + " feet of fence total");
                } 
                else
                    System.out.println("The ratio needs to be a positive number!");


    }

    } //end class

在 java 中,唯一的顶级 "things" 是 classes(以及类似的东西,例如接口和枚举)。函数不是顶级 "things"。它们只能存在于 class 中。因此,要调用它,您需要遍历 class,或遍历 class 的对象。

从您编写的代码来看,test 似乎是一个非静态方法。在这种情况下,您需要从 class 创建一个对象,并 运行 它的方法:

landEnclosure l = new landEnclosure();
l.test();

但是,您的意图似乎是让 'test' 成为静态方法。在那种情况下,将其声明为静态并以这种方式调用它:

landEnclosure.test();

附带说明一下,Java 中的惯例是先用大写字母命名 classes :

class LandEnclosure {

除了创建 landEnclosure 的新实例的明显建议外,您还可以创建 function static 并调用:

landEnclosure.test();