7-4 Design a rectangle type Rectangle

JAVA.Water.1
Design a class named Rectangle to represent rectangles. This class includes:
two double type data fields named width and height, which respectively represent the width and height of the rectangle. The default values ​​of width and height are both 1.
A no-argument construction method for creating a default rectangle.
A method to create a rectangle with specified width and height values.
A method called getArea() returns the area of ​​the rectangle.
A method called getPerimeter() returns the perimeter.
Write a test program to create two Rectangle objects, one has a width of 4 and a height of 40, and the other has a width of 3.5 and a height of 35.9. Display the width, height, area and perimeter of each rectangle in order.

Input format:

no

Output format:

Each line outputs the width, height, area and perimeter of a rectangle, separated by spaces

Input sample:

Here is a set of inputs. E.g:

Sample output:

The corresponding output is given here. E.g:

4.0 40.0 160.0 88.0
3.5 35.9 125.64999999999999 78.8

AC code:

import java.util.*;
class Rectangle
{
    
    
 	private double width;
    	private double height;
    	public Rectangle()
    	{
    
    
     		width=1.0;
     		height=1.0;
    	}
   	public Rectangle(double width,double height) 
    	{
    
    
     		this.width=width;
     		this.height=height;
    	}
    	public double getWidth() 
    	{
    
    
    		return width;
    	}
    	public double getHeight() 
    	{
    
    
     		return height;
    	}
 	public double getArea() 
    	{
    
    
  		return width*height;
    	}
    	public double getPerimeter() 
    	{
    
    
        	return 2*(width+height);
    	}
}
public class Main
{
    
    
 	public static void main(String[] args) 
    	{
    
    
     		Rectangle t1=new Rectangle(4,40);
     		Rectangle t2=new Rectangle(3.5,35.9);
     		System.out.println(t1.getWidth()+" "+t1.getHeight()+" "+t1.getArea()+" "+t1.getPerimeter());
     		System.out.println(+t2.getWidth()+" "+t2.getHeight()+" "+t2.getArea()+" "+t2.getPerimeter());
    	}
}

Guess you like

Origin blog.csdn.net/weixin_45989486/article/details/108750385