计算矩形周长和面积

时间:2014-07-08 07:08:53

标签: java oop object rectangles

我们应该创建一个程序来创建一个具有属性长度和宽度的类,默认值为1.0,并且还有获取周长和面积的方法。我已经完成了创建课程但我们必须在程序中测试它。这就是我的代码的样子:

public class Rectangle {
private double length, width;

public Rectangle() {
    length = 1.0;
    width = 1.0;
}
public Rectangle (double l, double w){
    length = l;
    width = w;
}
public void setLength(double l){
    length = l;
}
public void setWidth(double w){
    width = w;
}
public double getLength(){
    return length;
}
public double getWidth(){
    return width;
}
public double getArea(){
    return length*width;
}
public double getPerimeter(){
    return (2*length)+(2*width);
}
}

import java.util.Scanner;
public class TestRectangle {
public static void main(String[]args) {
    int choice;
    double area, perimeter;     
    Scanner keyboard = new Scanner (System.in);
    Rectangle rec1 = new Rectangle();

    System.out.print("Choose an action:\n" + "1. Set Length\n" + "2. Set Width\n" + "3. Exit\n" + "Choice: ");
    choice = keyboard.nextInt();

    switch(choice){
        case 1:
            System.out.print("Enter Length: ");
            l = input.nextDouble;
            rec1.setLength(i);
            System.out.print("Length: "+rec1.getLength());
            System.out.print("Width: "+w);
            System.out.print("Area: "+rec1.getArea);
            System.out.print("Perimeter: "+rec1.getPerimeter);
            break;
        case 2:
            System.out.print("Enter Width: ");
            w = input.nextDouble;
            rec1.setWidth(w);
            System.out.print("Length: "+l);
            System.out.print("Width: "+rec1.getWidth);
            System.out.print("Area: "+rec1.getArea);
            System.out.print("Perimeter: "+rec1.getPerimeter);
            break;
        case 3:
            System.exit();
    }
}
}

它不断发现错误'找不到符号。'

1 个答案:

答案 0 :(得分:3)

您缺少方法调用的括号。 getPerimetergetArea应为getPerimeter()getArea()

同样适用于nextDouble

编译时,java编译器会指出它认为问题的确切位置。看看这个图片:

enter image description here

编译器显示错误使用^字符的位置。请使用编译器提示来查找程序的语法错误。