目录
设计要求
设计流程图
程序代码
类Village代码
类MainClass代码
可以直接运行的代码
运行结果
类变量与实例变量的区别和类方法与实例方法的区别
idea的详细使用方法
设计要求
编写程序模拟两个村庄共同拥有一片森林;编写一个Village类,该类有一个静态的int型成员变量treeAmount用于模拟森林中树木的数量;在主类MainClass的main方法中创建了两个村庄,一个村庄改变了treeAmount值,另一个村庄查看treeAmount值。
设计流程图
程序代码
类Village代码
package com.yuan;
public class Village {
static int treeAmount;
//模拟森林中树木的数量
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;
}
}
类MainClass代码
package com.yuan;
public class MainClass {
public static void main(String[] args) {
Village xiaohe, dahe;
xiaohe = new Village("小河");
dahe = new Village("大河");
Village.treeAmount = 200;
int leftTree = Village.treeAmount;
System.out.println("森林中有" + leftTree + "棵树");
dahe.treePlanting(50);
System.out.println("大河村植树50棵后");
leftTree = Village.lookTreeAmount();
System.out.println("森林中有" + leftTree + "棵树");
dahe.fellTree(70);
leftTree = Village.lookTreeAmount();
System.out.println("森林中有" + leftTree + "棵树");
}
}
可以直接运行的代码
package com.yuan;
//这个包是自己建立的,所以如果引入不了的话就不用引用了,自己建一个
public class Village {
static int treeAmount;
//模拟森林中树木的数量
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;
}
public static void main(String[] args) {
Village xiaohe, dahe;
xiaohe = new Village("小河");
dahe = new Village("大河");
Village.treeAmount = 200;
int leftTree = Village.treeAmount;
System.out.println("森林中有" + leftTree + "棵树");
dahe.treePlanting(50);
System.out.println("大河村植树50棵后");
leftTree = Village.lookTreeAmount();
System.out.println("森林中有" + leftTree + "棵树");
dahe.fellTree(70);
leftTree = Village.lookTreeAmount();
System.out.println("森林中有" + leftTree + "棵树");
}
}
运行结果
类变量与实例变量的区别和类方法与实例方法的区别
详见
博主:浩瀚蓝天dephttps://blog.csdn.net/LSW_JAVADP/article/details/97558003