文章目录
- 第06章_面向对象编程(基础)拓展练习
- 1、圆类
- 2、学生类
- 3、MyInt类
- 4、MyDate日期类-1
- 5、MyDate日期类-2
- 6、数学计算工具类
- 7、常识工具类
- 8、学生对象数组
- 9、员工管理类-1
- 10、员工管理类-2
- 11、比较大小
- 12、数组排序和遍历
- 13、求三角形面积
- 14、图形工具类
- 15、Count类
- 16、PassParamDemo类
- 17、矩形类
- 18、矩形类
- 19、三角形类
- 20、猴子吃桃
第06章_面向对象编程(基础)拓展练习
1、圆类
(1)声明一个圆的图形类,包含实例变量/属性:半径
(2)在测试类的main中,创建2个圆类的对象,并给两个圆对象的半径属性赋值,最后显示两个圆的半径值、周长和面积值
提示:圆周率可以使用Math.PI
public class Circle {
double radius;
}
public class Exercise1 {
public static void main(String[] args) {
//创建两个Circle圆对象
Circle c1 = new Circle();
Circle c2 = new Circle();
//为两个圆对象的半径属性赋值
c1.radius = 1.2;
c2.radius = 2.5;
//显示
System.out.println("c1的半径:" + c1.radius + ",周长:" + 2 * Math.PI * c1.radius + ",面积:" + Math.PI * c1.radius * c1.radius);
System.out.println("c2的半径:" + c2.radius + ",周长:" + 2 * Math.PI * c2.radius + ",面积:" + Math.PI * c2.radius * c2.radius);
}
}
2、学生类
(1)声明一个学生类,包含实例变量/属性:姓名和成绩
(2)在测试类的main中,创建2个学生类的对象,并给两个学生对象的姓名和成绩赋值,最后输出显示
public class Student {
String name;
int score;
}
public class Exercise2 {
public static void main(String[] args) {
//创建2个学生类的对象
Student s1 = new Student();
Student s2 = new Student();
//给两个学生对象的姓名和成绩赋值
s1.name = "张三";
s1.score = 89;
s2.name = "李四";
s2.score = 74;
//显示
System.out.println("s1学生对象的姓名:" + s1.name + ",成绩:" + s1.score);
System.out.println("s2学生对象的姓名:" + s2.name + ",成绩:" + s2.score);
}
}
3、MyInt类
(1)声明一个MyInt类,
- 包含一个int类型的value属性
- 包含一个方法boolean isNatural()方法,用于判断value属性值是否是自然数。自然数是大于等于0的整数。
- 包含一个方法int approximateNumberCount()方法,用于返回value属性值的约数个数。在[1, value]之间可以把value整除的整数都是value的约数。
- 包含一个方法boolean isPrimeNumber()方法,用于判断value属性值是否是素数。如果value值在[1, value]之间只有1和value本身两个约数,并且value是大于1的自然数,那么value就是素数。
- 包含一个方法int[] getAllPrimeNumber()方法,用于返回value属性值的所有约数。返回[1, value]之间可以把value整除的所有整数。
(2)测试类的main中调用测试
public class MyInt {
int value;
public boolean isNatural(){
return value >= 0;
}
public int approximateNumberCount(){
int count = 0;
for(int i=1; i<=value; i++){
if(value%i==0){
count++;
}
}
return count;
}
public boolean isPrimeNumber(){
return value > 1 && approximateNumberCount()==2;
}
public int[] getAllApproximateNumber(){
int[] all = new int[approximateNumberCount()];
for(int i=1,j=0; i<=value; i++){
if(value%i==0){
all[j++] = i;
}
}
return all;
}
}
public class Exercise3 {
public static void main(String[] args) {
MyInt myInt1 = new MyInt();
myInt1.value = 8;
System.out.println("myInt1是" + myInt1.value);
System.out.println("myInt1是自然数吗:" + myInt1.isNatural());
System.out.println("myInt1的约数个数:" + myInt1.approximateNumberCount());
System.out.println("myInt1是素数吗:" + myInt1.isPrimeNumber());
int[] allPrimeNumber = myInt1.getAllApproximateNumber();
System.out.println("myInt1的所有约数有:");
for (int i = 0; i < allPrimeNumber.length; i++) {
System.out.println(allPrimeNumber[i]);
}
System.out.println("------------------------------------------");
MyInt myInt2 = new MyInt();
myInt2.value = 11;
System.out.println("myInt2是" + myInt2.value);
System.out.println("myInt2是自然数吗:" + myInt2.isNatural());
System.out.println("myInt2的约数个数:" + myInt2.approximateNumberCount());
System.out.println("myInt2是素数吗:" + myInt2.isPrimeNumber());
allPrimeNumber = myInt2.getAllApproximateNumber();
System.out.println("myInt2的所有约数有:");
for (int i = 0; i < allPrimeNumber.length; i++) {
System.out.println(allPrimeNumber[i]);
}
}
}
4、MyDate日期类-1
案例:
声明一个日期类MyDate,包含属性:年、月、日,并在MyDate类中声明几个方法:
1、boolean isLeapYear():判断当前日期的是闰年吗
2、void set(int y, int m, int d):修改年,月,日为新日期
3、void puls(int years, int months, int days):加上years年,months月,days天后的日期
并在测试类Exercise4的main方法中创建对象,并调用测试
public class MyDate {
int year;
int month;
int day;
public boolean isLeapYear(){
return year%4==0 && year%100!=0 || year%400==0;
}
public void set(int y, int m, int d){
year = y;
month = m;
day = d;
}
public void puls(int years, int months,int days){
day += days;
month += months;
year += years;
while(month>12){
month-=12;
year++;
}
while(true){
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10){
if(day>31){
day -= 31;
month++;
}else{
break;
}
}else if(month==4 || month==6 || month==9 || month==11){
if(day>30){
day -= 30;
month++;
}else{
break;
}
}else if(month==2){
if(year%4==0 && year%100!=0 || year%400==0){
if(day>29){
day -= 29;
month++;
}else{
break;
}
}else{
if(day>28){
day-=28;
month++;
}else{
break;
}
}
}else if(month == 12){
if(day>31){
day-=31;
month=1;
year++;
}else{
break;
}
}
}
}
}
public class Exercise4 {
public static void main(String[] args) {
MyDate my = new MyDate();
my.set(2019, 5, 13);
System.out.println(my.year + "年" + my.month + "月" + my.day + "日");
System.out.println("是闰年吗?" + my.isLeapYear());
my.puls(1, 70, 70);
System.out.println("再加1年70个月70天之后的日期是:");
System.out.println(my.year + "年" + my.month + "月" + my.day + "日");
}
}
5、MyDate日期类-2
声明一个日期类MyDate,
- 包含属性:年、月、日
- boolean isLeapYear():判断是否是闰年
- String monthName():根据月份值,返回对应的英语单词
- int totalDaysOfMonth():返回这个月的总天数
- int totalDaysOfYear():返回这一年的总天数
- int daysOfTheYear():返回这一天是当年的第几数
在测试类的main方法中,创建MyDate对象,赋值为当天日期值,调用方法测试。
public class MyDate {
int year;
int month;
int day;
boolean isLeapYear(){
return year%4==0 && year%100!=0 || year%400==0;
}
int totalDaysOfYear(){
return isLeapYear() ? 366 : 365;
}
int totalDaysOfMonth(){
if(month == 4 || month == 6 || month == 9 || month == 11){
return 30;
}
if(month == 2){
return isLeapYear() ? 29 : 28;
}
return 31;
}
int daysOfTheYear(){
int days = day;
for(int i=1; i<month; i++){
if(i==2){
days += isLeapYear() ? 29 : 28;
}else if(i==4 || i==6 || i==9 || i==11){
days += 30;
}else{
days += 31;
}
}
return days;
}
String monthName(){
String[] monthNames = {"January","February","March","April","May","June","July","August","September","October","November","December"};
return monthNames[month-1];
}
}
public class Exercise5 {
public static void main(String[] args) {
MyDate my = new MyDate();
my.year = 2021;
my.month = 12;
my.day = 29;
System.out.println("今年是闰年吗?" + my.isLeapYear());
System.out.println("月份名是" + my.monthName());
System.out.println("这个月总天数:" + my.totalDaysOfMonth());
System.out.println("这一年总天数:" + my.totalDaysOfYear());
System.out.println("这一天是这一年的几天?" + my.daysOfTheYear());
}
}
6、数学计算工具类
案例:
声明一个数学计算工具类MathTools,包含如下方法:
1、int add(int a, int b):求a+b
2、int subtract(int a,int b):求a-b
3、int mutiply(int a, int b):求a*b
4、int divide(int a, int b):求a/b
5、int remainder(int a, int b):求a%b
6、int max(int a, int b):求a和b中的最大值
7、int min(int a, int b):求a和b中的最小值
8、boolean equals(int a, int b):判断a和b是否相等
9、boolean isEven(int a):判断a是否是偶数
10、boolean isPrimeNumer(int a):判断a是否是素数
11、int round(double d):返回d的四舍五入后的整数值
声明一个Test06测试类,并在main方法中调用测试
public class MathTools {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int mutiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
return a / b;
}
public int remainder(int a, int b) {
return a % b;
}
public int max(int a, int b) {
return a > b ? a : b;
}
public int min(int a, int b) {
return a < b ? a : b;
}
public boolean equals(int a, int b) {
return a == b;
}
public boolean isEven(int a) {
return a % 2 == 0;
}
public boolean isPrimeNumber(int a){
for (int i = 2; i < a; i++) {
if(a%i == 0){
return false;
}
}
return true;
}
public int round(double d){
return (int)(d + 0.5);
}
}
public class Exercise6 {
public static void main(String[] args) {
MathTools tools = new MathTools();
int a = 5;
int b = 3;
System.out.println(a + "+" + b + "=" + tools.add(a,b));
System.out.println(a + "-" + b + "=" + tools.subtract(a,b));
System.out.println(a + "*" + b + "=" + tools.mutiply(a,b));
System.out.println(a + "/" + b + "=" + tools.divide(a,b));
System.out.println(a + "%" + b + "=" + tools.remainder(a,b));
System.out.println(a + "," + b + "的最大值:" + tools.max(a, b));
System.out.println(a + "," + b + "的最小值:" + tools.min(a, b));
System.out.println(a + "==" + b + "?" + tools.equals(a,b));
System.out.println(a + "是偶数?" + tools.isEven(a));
System.out.println(a + "是素数?" + tools.isPrimeNumber(a));
System.out.println("5.4四舍五入的结果:" + tools.round(5.4));
System.out.println("5.6四舍五入的结果:" + tools.round(5.6));
}
}
7、常识工具类
案例:
声明一个常识工具类CommonsTools,包含如下方法:
1、String getWeekName(int week):根据星期值,返回对应的英语单词
2、String getMonthName(int month):根据月份值,返回对应的英语单词
3、int getTotalDaysOfMonth(int year, int month):返回某年某月的总天数
4、int getTotalDaysOfYear(int year):获取某年的总天数
5、boolean isLeapYear(int year):判断某年是否是闰年
声明一个Test08测试类,并在main方法中调用测试
public class CommonsTools {
public String getWeekName(int week){
switch(week){
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
}
return "";
}
public String getMonthName(int month){
String[] all = {"January","February","March","April","May","June","July","August","September","October","November","December"};
if(month >= 1 && month <= 12){
return all[month-1];
}
return "";
}
public int getTotalDaysOfMonth(int year, int month){
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
if(isLeapYear(year)){
days[1]++;//闰年2月29天
}
if(month >= 1 && month <= 12){
return days[month-1];
}
return 0;
}
public int getTotalDaysOfYear(int year){
if(isLeapYear(year)){
return 366;
}
return 365;
}
public boolean isLeapYear(int year){
return year%4==0 && year%100!=0 || year%400==0;
}
}
public class Exercise7 {
public static void main(String[] args) {
CommonsTools tools = new CommonsTools();
System.out.println("3月:" + tools.getMonthName(3));
System.out.println("周三:" + tools.getWeekName(3));
System.out.println("2019-2的总天数:" + tools.getTotalDaysOfMonth(2019, 2));
System.out.println("2019年是否是闰年?" + tools.isLeapYear(2019) );
System.out.println("2019年的总天数:" + tools.getTotalDaysOfYear(2019));
}
}
8、学生对象数组
(1)定义学生类Student
- 声明姓名和成绩实例变量
- String getInfo()方法:用于返回学生对象的信息
(2)测试类的main中创建一个可以装3个学生对象的数组,从键盘输入3个学生对象的信息,并且按照学生成绩排序,显示学生信息
public class Student {
String name;
int score;
public String getInfo() {
return "姓名:" + name + ",成绩:" + score;
}
}
import java.util.Scanner;
public class Exercise8 {
public static void main(String[] args) {
//创建一个可以装3个学生对象的数组
Student[] arr = new Student[3];//只是申明这个数组,可以用来装3个学生,此时里面没有学生对象
//从键盘输入
Scanner input = new Scanner(System.in);
for(int i=0;i<arr.length; i++){
System.out.println("请输入第" + (i+1) + "个学生信息:");
arr[i] = new Student();
System.out.print("姓名:");
arr[i].name = input.next();
System.out.print("成绩:");
arr[i].score = input.nextInt();
}
input.close();
//先显示一下目前的顺序
System.out.println("排序之前,学生对象信息:");
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].getInfo());
}
System.out.println("------------------------------------------");
//冒泡排序
for(int i=1; i<arr.length; i++){
for(int j=0; j<arr.length-i; j++){
//arr[j] > arr[j+1]//错误的
if(arr[j].score > arr[j+1].score){
//交换两个元素,这里是两个学生对象,所以temp也得是Student类型
Student temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("排序之后,学生对象信息:");
//再显示一下目前的顺序
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].getInfo());
}
}
}
9、员工管理类-1
案例:
1、声明一个Employee员工类,
包含属性:编号(id)、姓名(name)、薪资(salary)、年龄(age),此时属性不私有化
包含方法:
(1)void printInfo():可以打印员工的详细信息
(2)void setInfo(int i, String n, double s, int a):可以同时给id,name,salary,age赋值
2、声明一个EmployeeManager类,包含如下方法:
(1)public void print(Emplyee[] all):遍历打印员工数组中的每个员工的详细信息
(2)public void sort(Employee[] all):将all员工数组按照年龄从高到低排序
(3)public void addSalary(Employee[] all, double increament):将all员工数组的每一个员工的工资,增加increament
3、声明Test05测试类
(1)public static void main(String[] args):在main方法中,创建Employee[]数组,并创建5个员工对象放到数组中,并为员工对象的属性赋值
(2)创建EmployeeManager对象,
(3)调用print方法,显示员工信息
(4)调用sort方法对员工数组进行按照年龄排序,并调用print方法,显示员工信息
(5)调用addSalary方法给每一个员工加薪1000元,并调用print方法,显示员工信息
public class Employee {
int id;
String name;
double salary;
int age;
void printInfo(){
System.out.println("编号:" + id + ",姓名:" + name + ",薪资:" + salary + ",年龄:" +age);
}
void setInfo(int i, String n, double s, int a){
id = i;
name = n;
salary = s;
age = a;
}
}
public class EmployeeManager {
public void print(Employee[] all){
for(int i=0; i<all.length; i++){
all[i].printInfo();
}
}
public void sort(Employee[] all){
for(int i=1; i<all.length; i++){
for(int j=0; j<all.length-i; j++){
//从高到低
if(all[j].age < all[j+1].age){
Employee temp = all[j];
all[j] = all[j+1];
all[j+1] = temp;
}
}
}
}
public void addSalary(Employee[] all, double increament){
for(int i=0; i<all.length; i++){
all[i].salary += increament;
}
}
}
public class Exercise9 {
public static void main(String[] args){
Employee[] all = new Employee[5];
all[0] = new Employee();
all[0].setInfo(1,"张三",10000,23);
all[1] = new Employee();
all[1].setInfo(2,"李四",12000,23);
all[2] = new Employee();
all[2].setInfo(3,"王五",8000,18);
all[3] = new Employee();
all[3].setInfo(4,"赵六",6000,20);
all[4] = new Employee();
all[4].setInfo(5,"钱七",15000,21);
EmployeeManager em = new EmployeeManager();
em.print(all);
System.out.println("------------------------------------------");
em.sort(all);
em.print(all);
System.out.println("------------------------------------------");
em.addSalary(all, 200);
em.print(all);
}
}
10、员工管理类-2
声明一个Employee员工类,包含属性:编号(id)、姓名(name)、薪资(salary)、年龄(age),包含如下方法:
- String getInfo():返回员工的详细信息,每一个
- void setInfo(int i, String n, double s, int a):可以同时给id,name,salary,age赋值
声明一个EmployeeManager员工管理类,包含:
- Employee[]类型的allEmployees,长度指定为5
- int类型的实例变量total,记录allEmployees数组实际存储的员工数量
- boolean addEmployee(Employee emp):添加一个员工对象到allEmployees数组中,如果数组已满,则不添加并提示数组已满
- Employee[] getEmployees():返回total个员工对象
在测试类的main中添加6个员工对象,并且遍历输出。
public class Employee {
int id;
String name;
double salary;
int age;
String getInfo(){
return "编号:" + id + ",姓名:" + name + ",薪资:" + salary + ",年龄:" +age;
}
void setInfo(int i, String n, double s, int a){
id = i;
name = n;
salary = s;
age = a;
}
}
public class EmployeeManager {
Employee[] allEmployees = new Employee[5];
int total;
boolean addEmployee(Employee emp){
if(total >= allEmployees.length){
System.out.println("数组已满");
return false;
}
allEmployees[total++] = emp;
return true;
}
Employee[] getEmployees(){
Employee[] results = new Employee[total];
for (int i = 0; i < results.length; i++) {
results[i] = allEmployees[i];
}
return results;
}
}
public class Exercise10 {
public static void main(String[] args) {
EmployeeManager em = new EmployeeManager();
Employee e1 = new Employee();
e1.setInfo(1,"刘一",11000,21);
Employee e2 = new Employee();
e2.setInfo(2,"陈二",12000,22);
Employee e3 = new Employee();
e3.setInfo(3,"张三",13000,23);
Employee e4 = new Employee();
e4.setInfo(4,"李四",14000,24);
Employee e5 = new Employee();
e5.setInfo(5,"王五",15000,25);
Employee e6 = new Employee();
e6.setInfo(6,"赵六",16000,26);
System.out.println("添加e1" + (em.addEmployee(e1)?"成功":"失败"));
System.out.println("添加e2" + (em.addEmployee(e2)?"成功":"失败"));
System.out.println("添加e3" + (em.addEmployee(e3)?"成功":"失败"));
System.out.println("添加e4" + (em.addEmployee(e4)?"成功":"失败"));
System.out.println("添加e5" + (em.addEmployee(e5)?"成功":"失败"));
System.out.println("添加e6" + (em.addEmployee(e6)?"成功":"失败"));
Employee[] employees = em.getEmployees();
for (int i = 0; i < employees.length; i++) {
System.out.println(employees[i].getInfo());
}
}
}
11、比较大小
(1)声明MathTools工具类,包含:
- public int compare(int a, int b):比较两个整数大小关系,如果第一个整数比第二个整数大,则返回正整数,如果第一个整数比第二个整数小,则返回负整数,如果两个整数相等则返回0;
- public int compare(double a, double b):比较两个小数大小关系,如果第一个小数比第二个小数大,则返回正整数,如果第一个小数比第二个小数小,则返回负整数,如果两个小数相等则返回0;
- public int compare(char a, char b):比较两个字符大小关系,如果第一个字符比第二个字符编码值大,则返回正整数,如果第一个字符比第二个字符编码值小,则返回负整数,如果两个字符相等则返回0;
(2)在测试类的main方法中调用
public class MathTools {
public int compare(int a, int b){
return a - b;
}
public int compare(double a, double b){
if(a > b){
return 1;
}else if(a < b){
return -1;
}
return 0;
}
public int compare(char a, char b){
return a - b;
}
}
public class Exercise11 {
public static void main(String[] args) {
MathTools tools = new MathTools();
System.out.println(tools.compare(4,7));
System.out.println(tools.compare(4.5, 7.3));
System.out.println(tools.compare('a', 'b'));
System.out.println(tools.compare(4.3, 7));
}
}
12、数组排序和遍历
(1)声明一个数组工具类ArraysTools,包含几个重载方法
- 重载方法系列1:可以为int[],double[],char[]数组实现从小到大排序
- public void sort(int[] arr)
- public void sort(double[] arr)
- public void sort(char[] arr)
- 重载方法系列2:toString方法,可以遍历int[],double[],char[]数组,遍历结果形式:[元素1,元素2,。。。]
- public String toString(int[] arr)
- public String toString(double[] arr)
- public String toString(char[] arr)
(2)在测试类的main方法中调用
public class ArraysTools {
public void sort(int[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length- i ; j++) {
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public void sort(double[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length- i ; j++) {
if(arr[j] > arr[j+1]){
double temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public void sort(char[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length- i ; j++) {
if(arr[j] > arr[j+1]){
char temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public String toString(int[] arr){
String result = "[";
for (int i = 0; i < arr.length; i++) {
if(i<arr.length-1){
result += arr[i] + ",";
}else{
result += arr[i] + "]";
}
}
return result;
}
public String toString(double[] arr){
String result = "[";
for (int i = 0; i < arr.length; i++) {
if(i<arr.length-1){
result += arr[i] + ",";
}else{
result += arr[i] + "]";
}
}
return result;
}
public String toString(char[] arr){
String result = "[";
for (int i = 0; i < arr.length; i++) {
if(i<arr.length-1){
result += arr[i] + ",";
}else{
result += arr[i] + "]";
}
}
return result;
}
}
public class Exercise12 {
public static void main(String[] args) {
ArraysTools tools = new ArraysTools();
int[] arr1 = {5,4,2,17,3};
tools.sort(arr1);
System.out.println(tools.toString(arr1));
double[] arr2 = {5.0 ,4.0, 2.0,17.0,3.0};
tools.sort(arr2);
System.out.println(tools.toString(arr2));
char[] arr3 = {'h','a','o','b','t'};
tools.sort(arr3);
System.out.println(tools.toString(arr3));
}
}
13、求三角形面积
(1)声明一个图形工具类GraphicTools,包含两个重载方法
- 方法1:public double triangleArea(double base, double height),根据底边和高,求三角形面积,
- 方法2:public double triangleArea(double a, double b, double c),根据三条边,求三角形面积,根据三角形三边求面积的海伦公式:
(2)在测试类的main方法中调用
public class GraphicTools {
public double triangleArea(double base, double height){
if(base > 0 && height > 0) {
return base * height / 2;
}
return 0;
}
public double triangleArea(double a, double b, double c){
if(a > 0 && b > 0 && c > 0 && a + b > c && b + c > a && a + c > b){
double p = (a + b + c)/2;
return Math.sqrt(p * (p-a) * (p-b) * (p-c));
}
return 0;
}
}
public class Exercise13 {
public static void main(String[] args) {
GraphicTools tools = new GraphicTools();
System.out.println(tools.triangleArea(3, 4));
System.out.println(tools.triangleArea(3,4,5));
}
}
14、图形工具类
案例:
声明一个图形工具类GraphicTools,包含如下方法:
1、void printRectangle():该方法打印5行5列*矩形
2、void printRectangle(int line, int column, String sign):该方法打印line行colomn列由sign组成的矩形
3、double getTriangleArea(double base, double height):根据底边和底边对应的高求三角形面积
4、double getTriangleArea(double a, double b, double c):根据三角形的三条边求三角形面积,如果a,b,c不能组成三角形,打印不能组成三角形,并返回0.0
声明Test02测试类,并在main方法中调用测试
public class GraphicTools {
void printRectangle() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print("*");
}
System.out.println();
}
}
void printRectangle(int line, int column, String sign) {
for (int i = 1; i <= line; i++) {
for (int j = 1; j <= column; j++) {
System.out.print(sign);
}
System.out.println();
}
}
double getTriangleArea(double base, double height) {
return base * height / 2;
}
double getTriangleArea(double a, double b, double c) {
if(a>0 && b>0 && c>0 && a+b>c && a+c>b && b+c >a){
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}else{
System.out.println(a +"," + b +"," + c + "不能构成三角形");
return 0;
}
}
}
public class Exercise14 {
public static void main(String[] args) {
GraphicTools tools = new GraphicTools();
tools.printRectangle();
System.out.println("--------------------------");
tools.printRectangle(5, 10, "#");
System.out.println("--------------------------");
System.out.println("底边为3,高为4的三角形面积:" + tools.getTriangleArea(3, 4));
System.out.println("边为3,4,5的三角形面积:" + tools.getTriangleArea(3, 4, 5));
}
}
15、Count类
在Count类中,声明如下方法:
1、public long sum(int… nums):求0~n个整数的累加和,如果没有传参,就返回0
2、public int max(int a, int… others):求1~n个整数中的最大值
3、public String concat(String… strings):求0~n个字符串的拼接结果
4、public boolean isEven(int… nums):判断0~n个整数是否都是偶数,如果都是偶数,返回true,否则返回false
声明一个Test01测试类,并在main方法中调用测试
public class Count{
public long sum(int... nums){
long sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum;
}
public int max(int a, int... others){
int max = a;
for (int i = 0; i < others.length; i++) {
if(others[i] > max){
max = others[i];
}
}
return max;
}
public String concat(String... strings){
String result = "";
for (int i = 0; i < strings.length; i++) {
result += strings[i];
}
return result;
}
public boolean isEven(int... nums){
for (int i = 0; i < nums.length; i++) {
if(nums[i]%2 !=0){
return false;
}
}
return true;
}
}
public class Exercise15 {
public static void main(String[] args) {
Count c = new Count();
System.out.println("1,2,3,4,5的总和:" + c.sum(1,2,3,4,5));
System.out.println("3,4,2,1的最大值是:" + c.max(3,4,2,1));
System.out.println("尚,硅,谷,好拼接的结果:" + c.concat("尚","硅","谷","好"));
System.out.println("2,4,6,8是否都是偶数:" + c.isEven(2,4,6,8));
}
}
16、PassParamDemo类
在PassParamDemo类中,声明如下方法,并体会方法的参数传递机制,并尝试画图分析
- void doubleNumber(int num):将num变为原来的2倍大
- void toUpperCase(char letter):将letter的小写字母转为大写字母
- void expandCircle(Circle c,double times):将Circle的c对象的半径扩大为原来的times倍。圆Circle类,包含radius属性。
- void doubleElement(int[] arr):把arr数组的元素扩大2倍
- void grow(int[] arr):将arr数组的长度变为原来的1.5倍
public class PassParamDemo {
void doubleNumber(int num){
num *= 2;
}
void toUpperCase(char letter){
letter -= 32;
}
void expandCircle(Circle c, double times){
c.radius *= times;
}
void doubleElement(int[] arr){
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2;
}
}
void grow(int[] arr){
arr = new int[arr.length*2];
}
}
在main方法中调用上面的方法后,请分析运行结果。
public class Exercise16 {
public static void main(String[] args) {
PassParamDemo demo = new PassParamDemo();
int x = 1;
demo.doubleNumber(x);
System.out.println("x = " + x);
char c = 'a';
demo.toUpperCase(c);
System.out.println("c = " + c);
Circle circle = new Circle();
circle.radius = 1;
demo.expandCircle(circle, 5);
System.out.println("circle.radius = " + circle.radius);
int[] arr = {1,2,3,4,5};
demo.doubleElement(arr);
System.out.println("调用doubleElement方法之后:");
System.out.println("arr数组的元素:" );
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
demo.grow(arr);
System.out.println("调用grow方法之后:arr的数组长度:" + arr.length);
System.out.println("arr数组的元素:" );
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
17、矩形类
案例:
1、声明矩形类Rectangle
(1)包含属性:长和宽,要求属性私有化
(2)给每一个属性提供get/set方法
(3)public double getArea()
(4)public double getPerimeter()
(5)提供getInfo()返回矩形对象的信息
例如:长:4,宽:2,面积:8,周长:12
2、测试类Exercise17,
(1)在main()方法中创建Rectangle对象,并用set方法为属性赋值
(2)调用get方法打印属性的值,调用getArea打印面积,调用getPerimeter打印周长
(3)再次调用set方法修改属性的值为原来属性值的两倍
(4)调用getInfo方法打印矩形信息
public class Rectangle {
private double length;
private double width;
public void setLength(double chang){
length = chang;
}
public double getLength(){
return length;
}
public void setWidth(double kuan){
width = kuan;
}
public double getWidth(){
return width;
}
public double getArea(){
return length * width;
}
public double getPerimeter(){
return 2 * (length + width);
}
public String getInfo(){
return "长:" + length + ",宽:" + width + ",面积:" + getArea() + ",周长:" + getPerimeter();
}
}
public class Exercise17 {
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.setLength(2);
r.setWidth(1);
System.out.println("长:" + r.getLength());
System.out.println("宽:" + r.getWidth());
System.out.println("面积:" + r.getArea());
System.out.println("周长:" + r.getPerimeter());
r.setLength(r.getLength()*2);
r.setWidth(r.getWidth()*2);
System.out.println(r.getInfo());
}
}
18、矩形类
(1)定义矩形类Rectangle
- 声明实例变量长和宽,全部私有化private,
- 提供相应的get/set方法,如果set方法的参数值<=0,则提示矩形的长和宽必须是正数
- 声明public double area(),返回矩形面积
- 声明public double perimeter():返回矩形的周长
- 声明public String getInfo():返回矩形的长、宽、面积、周长信息
(2)测试类的main中创建一个可以装3个矩形对象的数组,并调用set方法为对象的属性赋值,依次长是8,7,6,宽是2,3,4
- 遍历输出矩形对象数组
- 按照矩形对象的length属性值从小到大排序后,遍历输出矩形对象数组
- 按照矩形对象的面积从小到大排序后,遍历输出矩形对象数组
public class Rectangle {
private double length;
private double width;
public double getLength() {
return length;
}
public void setLength(double l) {
if(l <= 0){
System.out.println("矩形的长必须是正数");
return;
}
length = l;
}
public double getWidth() {
return width;
}
public void setWidth(double w) {
if(w <= 0){
System.out.println("矩形的宽必须是正数");
return;
}
width = w;
}
public double area(){
return length * width;
}
public double perimeter(){
return 2 * (length + width);
}
public String getInfo(){
return "长:" + length + ",宽:" + width + ",面积:" + area() +",周长:" + perimeter();
}
}
public class Exercise18 {
public static void main(String[] args) {
Rectangle[] arr = new Rectangle[3];
arr[0] = new Rectangle();
arr[0].setLength(8);
arr[0].setWidth(2);
arr[1] = new Rectangle();
arr[1].setLength(7);
arr[1].setWidth(3);
arr[2] = new Rectangle();
arr[2].setLength(6);
arr[2].setWidth(4);
System.out.println("原始数据:");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getInfo());
}
System.out.println("按照length从小到大排序:");
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length-i; j++) {
if(arr[j].getLength() > arr[j+1].getLength()){
Rectangle temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getInfo());
}
System.out.println("按照面积从小到大排序:");
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length-i; j++) {
if(arr[j].area() > arr[j+1].area()){
Rectangle temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getInfo());
}
}
}
19、三角形类
(1)定义三角形类Triangle,
- 声明实例变量a,b,c,代表三角形三条边,全部私有化private,
- 提供每条边的get方法,
- 提供public void setBases(double a, double b, double c):要求参数a,b,c的值必须大于等于0,且满足三角形三边关系要求(即任意两边之后大于第三边),否则提示错误信息
- 声明public double area(),返回三角形面积
- 声明public double perimeter():返回三角形周长
- 声明public String getInfo():返回三角形的三条边,面积和周长
(2)测试类的main中创建一个三角形对象,并调用相应方法
public class Triangle {
private double a;
private double b;
private double c;
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public void setBases(double a, double b,double c){
if(a<=0 || b<=0 || c<=0){
System.out.println("三角形的边长必须是正数");
}else if(a+b<=c || a+c<=b || b+c<=a){
System.out.println("三角形任意两边之后必须大于第三边");
}else{
this.a = a;
this.b = b;
this.c = c;
}
}
public double area(){
double p = (a+b+c)/2;
return Math.sqrt(p*(p-a)*(p-b)*(p-c));
}
public double perimeter(){
return a+b+c;
}
public String getInfo(){
return "边长:" + a + "," + b + "," + c +",面积:" + area() +",周长:" + perimeter();
}
}
public class Exercise19 {
public static void main(String[] args) {
Triangle t = new Triangle();
t.setBases(1,2,3);
System.out.println(t.getInfo());
t.setBases(3,4,5);
System.out.println(t.getInfo());
}
}
20、猴子吃桃
猴子吃桃子问题,猴子第一天摘下若干个桃子,当即吃了所有桃子的一半,还不过瘾,又多吃了一个。
第二天又将仅剩下的桃子吃掉了一半,又多吃了一个。以后每天都吃了前一天剩下的一半多一个。
到第十天,只剩下一个桃子。试求第一天共摘了多少桃子?
提示:
getPeachNum(n) - (getPeachNum(n)/2 + 1) = getPeachNum(n + 1)
--> getPeachNum(n) = 2 * ( getPeachNum(n + 1) + 1)
public class PeachNumberTest {
public static void main(String[] args) {
PeachNumberTest test = new PeachNumberTest();
for(int i = 1;i <= 10;i++){
System.out.println("第" + i + "天,有" + test.getPeachNum(i) + "个桃");
}
}
public int getPeachNum(int n){
if(n == 10){
return 1;
}else{
return 2 * getPeachNum(n + 1) + 2;
}
}
}