方法参数的问题... Java

时间:2016-11-01 01:11:30

标签: java oop methods

@Rogue这是我设置的新方式......我目前正在使用"找不到符号"错误。我仔细检查了我的对象(r​​ectangle4)。 有什么想法吗?再次感谢兄弟......

package rectanglewithprivatedatafields;

class RectangleTestFile
{
public static void main(String[] args)
{
    double lengths = rectangle4.getLengths();
    double widths = rectangle4.getAreas();

//rectangle object 4
RectangleWithPrivateDataFields rectangle4 = new RectangleWithPrivateDataFields();
System.out.println("\nUser Specified Rectangle 4");
System.out.println("Please enter the appropriates sizes for your rectangle: \n");
System.out.println(rectangle4.getWidths());
System.err.println(rectangle4.getLengths());
System.out.println(rectangle4.getPerimeters(rectangle4.getLengths(), rectangle4.getWidths())); 
System.out.println(rectangle4.getAreas(rectangle4.getLengths(),rectangle4.getWidths()));
 }//main
}

2 个答案:

答案 0 :(得分:0)

而不是rectangle4.getPerimeters(lengths, widths)你的意思是rectangle4.getPerimeters(rectangle4.getLengths(), rectangle4.getWidths())吗?

您的实用程序类没有任何私有成员变量,只有公共访问器方法。

答案 1 :(得分:0)

lengthswidths不是主要方法中的变量,因此请填写:

int lengths = rectangle4.getLengths();
int widths = rectangle4.getWidths();

由于这些方法读取输入,因此您应该只调用一次。另外,我记得Scanner消耗System.in流,所以我只会做一次。继续前进(为了面向对象的编程),我会让构造函数接受一个Scanner来构建自己,然后让方法返回我需要的值:

//Simple, short class names are easier to work with
public class Rectangle {

    //length and width is data, or "state" of our rectangle, so store it
    private final int length;
    private final int width;

    //Allow creating it without requiring input
    public Rectangle(int width, int length) {
        this.width = width;
        this.length = length;
    }

    //We create ourselves given a Scanner which we can take input from
    public Rectangle(Scanner input) {
        System.out.print("Length: ");
        this.length = input.nextDouble();
        System.out.print("Width: ");
        this.width = input.nextDouble();
    }

    //Calculate based around known information
    public double getArea() {
        return this.length * this.width;
    }

    //Calculate based around known information
    public double getPerimeter() {
        return 2 * (this.length + this.width);
    }

    //getter
    public int getLength() {
        return this.length;
    }

    //getter
    public int getWidth() {
        return this.width;
    }

}

这样就可以这样调用它:

public static final void main(String... args) {
    Scanner input = new Scanner(System.in); //make once
    Rectangle rect = new Rectangle(input); //let our rectangle do all the work
    //Simple!
    System.out.println("Your rectangle has a width of " + rect.getWidth()
            + ", a length of " + rect.getLength()
            + ", the perimeter " + rect.getPerimeter()
            + ", and an area of " + rect.getArea());
}

这里的关键思想是数据和角色的分离 - Rectangle将管理信息的所有方面和自身的创造;您是手动提供lengthwidth,还是提供获取该信息的方法(我们的Scanner)。 Rectangle将存储它所需的信息,并返回我们想要的任何其他信息(我们的方法)。这使得类的计算和使用非常简单(您传递输入,现在您的工作从外部角度完成)。

相关问题