如何在客户端调用构造函数?

时间:2019-01-31 03:37:11

标签: java

我正在尝试编写一个程序,该程序需要用户输入并创建一个矩形。该程序将验证用户输入的有效矩形,如果是,将输出“面积”和“周长”。第一个屏幕截图是Test客户端,第二个是主要客户端。当我运行Rectangle.java时,它可以很好地编译,但是当我编译Test.java时,它说:“错误:找不到符号布尔结果= ValidRectangle(宽度,长度);”它说找不到ValidRectangle,Area和Perimeter。救命!不确定为什么不能自动识别Rectangle.java中的构造函数

我尝试通过Google搜索此错误,但没有找到太多帮助。我以为会自动识别构造函数?

// Rectangle.java

import java.util.Scanner;

public class Rectangle {

/*Validates that the rectangle is acceptable*/

public static boolean ValidRectangle (double width, double length) {

    if (width + length > 30)

        return true;
    else
        return false;
}

/*Calculates the area of the rectangle*/

public static double Area (double width, double length) {
    return (width * length);
}

/*Calculates the perimeter of the rectangle*/

public static double Perimeter (double width, double length) {
    return (2 * (width + length));
}

}

// Test.java

import java.io.*;
import java.util.Scanner;  

public class Test {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print ("Enter the width of the rectangle : ");
    double width = input.nextFloat();

    System.out.print ("Enter the length of the rectangle : ");
    double length = input.nextFloat();

    System.out.println ("Entered Width : "+width);
            System.out.println ("Entered length : "+length);

    boolean result = ValidRectangle (width, length);

    if(result==false)
         System.out.println("This is invalid rectangle. Try 
                 again...");
    else {
         System.out.println("Area : "+Area (width, length));
         System.out.println("Perimeter : "+Perimeter (width, 
                 length));
               }
           }
       }

3 个答案:

答案 0 :(得分:2)

ValidRectangle是属于类Rectangle的方法。 ValidRectangle是静态的,因此您不必实例化Rectangle对象。您可以这样称呼它:

boolean result = Rectangle.ValidRectangle(width, length);

作为旁注,我建议您遵循流行的Java代码样式约定,例如Google's。具体来说,您应该name your methods使用lowerCamelCase

答案 1 :(得分:1)

使用Rectangle.ValidRectangle(width, length);或添加一个导入静态语句,该语句将允许您在Rectangle中调用所有静态函数而无需引用它:import static (package containing Rectangle).Rectangle;

答案 2 :(得分:0)

您应该导入静态方法 在代码“ public class Test”之前添加import static,如下所示

...
import static your.package.Rectangle.ValidRectangle ;
public class Test {...

...