面积周长练习
定义一个矩形类Rectangle:(知识点:对象的创建和使用)
1 定义三个方法:getArea()求面积、getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长。
2 有2个属性:长length、宽width
3 创建一个Rectangle对象,并输出相关信息
1 package com.yhqtv.demo02.ThreadPool; 2 3 4 import java.util.Scanner; 5 6 public class Test1 { 7 public static void main(String[] args) { 8 9 Rectangle r = new Rectangle(); 10 11 System.out.println("请输入两个数字"); 12 Scanner s1 = new Scanner(System.in); 13 Scanner s2 = new Scanner(System.in); 14 int i = s1.nextInt(); 15 int i1 = s2.nextInt(); 16 if (i < 0 || i1 < 0) { 17 System.out.println("超出正常范围"); 18 return; 19 } 20 r.setLength(i); 21 r.setWidth(i1); 22 r.showAll(r); 23 } 24 25 26 } 27 28 29 class Rectangle { 30 private int length; 31 private int width; 32 33 public Rectangle(int length, int width) { 34 this.length = length; 35 this.width = width; 36 } 37 38 public Rectangle() { 39 40 } 41 42 public int getLength() { 43 return length; 44 } 45 46 public void setLength(int length) { 47 this.length = length; 48 } 49 50 public int getWidth() { 51 return width; 52 } 53 54 public void setWidth(int width) { 55 this.width = width; 56 } 57 58 public int getArea(Rectangle r) { 59 int area = r.getWidth() * r.getLength(); 60 return area; 61 } 62 63 public int getPer(Rectangle r) { 64 int per = 2 * (r.getLength() + r.getWidth()); 65 return per; 66 } 67 68 public void showAll(Rectangle r) { 69 System.out.println( 70 "矩形的长:" + r.getLength() + 71 "宽:" + r.getWidth() + 72 "面积:" + this.getArea(r) + 73 "周长:" + this.getPer(r)); 74 } 75 }
"D:\Program Files\
请输入两个数字
-9
6
超出正常范围
Process finished with exit code 0
个人官网yhqtv.com

浙公网安备 33010602011771号