j2se之方法的封装

来源:互联网 发布:java实现聊天室功能 编辑:程序博客网 时间:2024/05/18 01:50
package myTest;


public class Lesson18 {


/**
* author荀小贱
* 要求:建立矩形类,功能,完成矩形的面积和周长,要求矩形的长和宽必须大于0
* 目的:有效的将方法封装起来
*/
private int length;
private int width;
private int area;
private int circle;

public Lesson18(int length, int width){
this.length = length;
this.width = width;
}

public int area(){
this.area = length * width;
return area;
}
public int circle(){
this.circle = (length + width) * 2;
return circle;
}
public boolean is(){
boolean is = false;
if(this.width > 0 && this.length > 0){
is = true;
}
return is;
}
}



package myTest;


import java.util.Scanner;


public class TestLesson18 {
/**
* author荀小贱
* 主测试类
*/
public static void main(String[] args) {
String str = "y";
while (str.equals("y")) {
int[] list = input();
Lesson18 test = new Lesson18(list[0], list[1]);
if (test.is()) {
System.out.println("矩形的面积为:" + test.area());
System.out.println("矩形的周长为:" + test.circle());
} else {
System.out.println("您输入的有误");
}
inputN("是否继续?如果继续请按Y");
}
}


// 将输入的长与宽存入数组当中
public static int[] input() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入矩形的长:");
int num1 = sc.nextInt();
System.out.println("请输入矩形的宽:");
int num2 = sc.nextInt();
int[] list = {num1,num2};
return list;
}


// 是否继续
public static String inputN(String str) {
Scanner sc = new Scanner(System.in);
System.out.println(str);
String s = sc.next();
return s;
}


}

原创粉丝点击