1. 程式人生 > >第四章 實驗三 共同的森林

第四章 實驗三 共同的森林

實驗目的:

               掌握類變數與例項變數,以及類方法與例項方法的區別

Village.java

public class Village {
static int treeAmount;
int peopleNumber;
String name;
Village(String s){
 name=s;   
}
void treePlanting(int n){
    treeAmount=treeAmount+n;
    System.out.println(name+"植樹"+n+"棵");
}
void fellTree(int n){
    if(treeAmount-n>=0){
        treeAmount=treeAmount-n;
        System.out.println(name+"伐樹"+n+"棵");
    }
    else{
        System.out.println("無樹木可伐");
    }
}
static int lookTreeAmount(){
    return treeAmount;
}
void addPeopleNumber(int n){
    peopleNumber=peopleNumber+n;
    System.out.println(name+"增加了"+name+"人");
}
}

MainClass1.java
public class MainClass1 {

   
    public static void main(String[] args) {
        Village zhaoZhuang,maJiaHeZhi;
        zhaoZhuang=new Village("趙莊");
        maJiaHeZhi=new Village("馬家河子");
        zhaoZhuang.peopleNumber=100;
        maJiaHeZhi.peopleNumber=150;
        Village.treeAmount=200;
        int leftTree=Village.treeAmount;
        System.out.println("森林中有"+leftTree+"棵樹");
        maJiaHeZhi.treePlanting(50);
        leftTree=Village.lookTreeAmount();
        System.out.println("森林中有"+leftTree+"棵樹");
        maJiaHeZhi.fellTree(70);
        leftTree=Village.lookTreeAmount();
        System.out.println("森林中有"+leftTree+"棵樹");
        System.out.println("趙莊的人口:"+zhaoZhuang.peopleNumber);
        zhaoZhuang.addPeopleNumber(12);
        System.out.println("趙莊的人口:"+zhaoZhuang.peopleNumber);
        System.out.println("馬家河子的人口:"+maJiaHeZhi.peopleNumber);
        maJiaHeZhi.addPeopleNumber(10);
        System.out.println("馬家河子的人口:"+maJiaHeZhi.peopleNumber);
        
    }
}

執行結果: