Zero Zero - 2 months ago 8
Java Question

The method ____ is undefined for the type ____

Okay so I have a homework assignment and I'm having difficulty calling a method on my main class that is in another class.

Basically the "test" method is in the landEnclosure.java class and I'm trying to call it on my main class which is landAndEat.java

They're both inside the same package:

Image

This is the main class where I'm trying to call the method:

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

} //end class

} //end main


This is the class where the method is being created:

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

Answer

In java the only top level "things" are classes (and similar stuff such as interfaces and enums). Functions are not top level "things". They can exist only inside a class. Thus to call it you need to go through that class, or through an object of that class.

From the code you have written it seems that test is a non static method. In that case you need to create an object from that class, and run the method on it :

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

However, it seems that your intention is for 'test' to be a static method. In that case, declare it static and call it that way :

landEnclosure.test();

On a side note, the convention in Java is to name classes with an upper case first :

class LandEnclosure {