定义图形接口,该接口有计算图形面积和周长的方法,实体类有长方形、圆形、三角形:
package com.stu.Demo1;
interface Graph{
void area();
void perimeter();
}
class rectangle implements Graph{
private int length;
private int wide;
public rectangle(int length,int wide){
this.length = length;
this.wide = wide;
}
@Override
public void area() {
System.out.println("这个图形是长方形。");
System.out.println("这个图形的面积是"+(this.length*this.wide));
}
@Override
public void perimeter() {
System.out.println("这个图形的周长是:"+2*(this.length+this.wide));
}
}
class circle implements Graph{
private int radius;
public circle(int radius){
this.radius = radius;
}
@Override
public void area() {
System.out.println("这个图形是圆形。");
System.out.println("这个图形的面积是:"+this.radius*this.radius*3.14);
}
@Override
public void perimeter() {
System.out.println("这个图形的周长是:"+2*3.14*this.radius);
}
}
class triangle implements Graph{
private int a;
private int b;
private int c;
public triangle(int a,int b,int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public void area() {
System.out.println("这个图形是三角形。");
System.out.println("这个图形的面积是:"+a*b*c);
}
@Override
public void perimeter() {
System.out.println("这个图形的周长是:"+(a+b+c));
}
}
public class ch12 {
public static void show(Graph h){
h.area();
h.perimeter();
}
public static void main(String[]args){
show(new rectangle(12,2));
show(new circle(2));
show(new triangle(1,2,3));
}
}
古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?
package com.stu.Demo1;
import java.util.Scanner;
public class ch13 {
public static int fibo(int a) {
if (a == 0)
return a;
else if (a == 1)
return a;
else
return fibo(a - 1) + fibo(a - 2);
}
public static void main(String[]args){
System.out.println("请输入这是第几个月:");
Scanner scan = new Scanner(System.in);
int b = scan.nextInt();
System.out.println("该月的兔子总数是:"+fibo(b));
}
}