Design a rectangle class Rectangle (Java)

Design a class named Rectangle to represent rectangles. This class includes: Two double data fields named width and height, which represent the width and height of the rectangle respectively. The default values ​​of width and height are both 1. A no-argument construction method. A rectangle construction method that specifies values ​​for width and height. A method called getArea() returns the area of ​​this rectangle. A method called getPerimeter() returns the perimeter of this rectangle.

The class name is:
Rectangle

Sample referee test procedure:

import java.util.Scanner;
/* 你的代码将被嵌入到这里 */

public class Main {
    
    
  public static void main(String[] args) {
    
    
    Scanner input = new Scanner(System.in);

    double w = input.nextDouble();
    double h = input.nextDouble();
    Rectangle myRectangle = new Rectangle(w, h);
    System.out.println(myRectangle.getArea());
    System.out.println(myRectangle.getPerimeter());

    input.close();
  }
}

Input example:
3.14 2.78

Sample output:
8.7292
11.84

class Rectangle {
    
    
    double width=1;
    double height=1;

    public double getArea(){
    
    
        return width*height;
    }
    public double getPerimeter(){
    
    
        return (width+height)*2;
    }

    public Rectangle(){
    
    

    }

    public Rectangle(double width, double height) {
    
    
        this.width = width;
        this.height = height;
    }
}

Guess you like

Origin blog.csdn.net/weixin_51430516/article/details/115119757