Java 面向对象编程:计算长方形的周长和面积

本示例演示了如何使用 Java 类和对象来计算长方形的周长和面积。学习如何定义类、构造函数、成员变量和方法,并使用它们来创建和操作长方形对象。

类定义

import java.util.Scanner;

class Rect {
    private int length;
    private int width;

    public Rect(int length) {
        if (length > 0) {
            this.length = length;
            this.width = length;
        } else {
            this.length = 0;
            this.width = 0;
        } 
    }

    public Rect(int length, int width) {
        if (length > 0 && width > 0) {
            this.length = length;
            this.width = width;
        } else {
            this.length = 0;
            this.width = 0;
        } 
    }

    public int getLength() {
        return length;
    }

    public int getWidth() {
        return width;
    }

    public int getPerimeter() {
        return 2 * (length + width);
    }

    public int getArea() {
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (input.hasNext()) {
            int length = input.nextInt();
            if (length <= 0) {
                System.out.println("0 0 0 0");
                continue;
            }

            int width = 0;
            if (input.hasNextInt()) {
                width = input.nextInt();
                if (width <= 0) {
                    System.out.println("0 0 0 0");
                    continue;
                }
            }

            Rect rect = new Rect(length, width);
            System.out.println(rect.getLength() + " " + rect.getWidth() + " " + rect.getPerimeter() + " " + rect.getArea());
        }
        input.close();
    }
}

代码说明:

  1. 定义 Rect 类: 该类表示一个长方形,包含长 length 和宽 width 两个私有成员变量。
  2. 构造函数: 提供了两个构造函数,一个用于创建正方形,另一个用于创建普通长方形。构造函数会根据输入的边长和宽进行初始化,并处理负数情况,确保长和宽始终非负。
  3. 成员方法: 提供了 getLengthgetWidthgetPerimetergetArea 方法,分别用于获取长方形的长、宽、周长和面积。
  4. 主函数 main: 在主函数中,使用 Scanner 从标准输入读取用户输入的数据,并根据输入创建相应的 Rect 对象。最后,输出长方形的长、宽、周长和面积。

代码使用

输入格式:

输入多组数据;

一行中若有1个整数,表示正方形的边长;

一行中若有2个整数(中间用空格间隔),表示长方形的长度、宽度。

若输入数据中有负数,则不表示任何图形,长、宽均为0。

输出格式:

每行测试数据对应一行输出,格式为:

长度 宽度 周长 面积(数据之间有1个空格分隔)

输入样例:

1
2 3
4 5
2
-2
-2 -3

输出样例:

1 1 4 1
2 3 10 6
4 5 18 20
2 2 8 4
0 0 0 0
0 0 0 0

总结

本示例展示了如何使用 Java 类和对象来模拟现实世界中的概念,并通过成员变量和方法来操作对象。学习本示例可以帮助您更好地理解面向对象编程的概念和应用。

Java 面向对象编程:计算长方形的周长和面积

原文地址: https://www.cveoy.top/t/topic/bwd9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录