计算长方形的周长和面积(类和对象)_JAVA
生活随笔
收集整理的這篇文章主要介紹了
计算长方形的周长和面积(类和对象)_JAVA
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
設計一個長方形類Rect,計算長方形的周長與面積。
成員變量:整型、私有的數據成員length(長)、width(寬);
構造方法如下:
(1)Rect(int length) —— 1個整數表示正方形的邊長
(2)Rect(int length, int width)——2個整數分別表示長方形長和寬
成員方法:包含求面積和周長。(可適當添加其他方法)
要求:編寫主函數,對Rect類進行測試,輸出每個長方形的長、寬、周長和面積。
Input
輸入多組數據;
一行中若有1個整數,表示正方形的邊長;
一行中若有2個整數(中間用空格間隔),表示長方形的長度、寬度。
若輸入數據中有負數,則不表示任何圖形,長、寬均為0。
Output
每行測試數據對應一行輸出,格式為:(數據之間有1個空格)
長度 寬度 周長 面積
Sample
Input
1
2 3
4 5
2
-2
-2 -3
Output
1 1 4 1
2 3 10 6
4 5 18 20
2 2 8 4
0 0 0 0
0 0 0 0
Hint
import java.util.*;class Rect {int length, width;public Rect(int length, int width) {if(length < 0)length = 0;if(width < 0)width = 0;this.length = length;this.width = width;}public Rect(int length) {this(length, length);}public int area() {return length * width;}public int circu() {return 2 * (length + width);}public String toStr() {String res = length +" "+width+" "+circu() +" "+area();return res;} }public class Main {public static void main(String args[]){Scanner reader = new Scanner(System.in);while(reader.hasNext()){String ch = reader.nextLine();String a[] = ch.split(" ");int c[] = new int[5];int i;for(i = 0; i < a.length; i++) {c[i] = Integer.parseInt(a[i]);}if(i == 1) {Rect x = new Rect(c[0]);System.out.println(x.toStr());}else if(i == 2) {Rect x = new Rect(c[0], c[1]);System.out.println(x.toStr());}}reader.close();}}總結
以上是生活随笔為你收集整理的计算长方形的周长和面积(类和对象)_JAVA的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 整理音乐_JAVA
- 下一篇: 计算各种图形的周长(接口与多态)_JAV