[Java] 纯文本查看 复制代码 package tree;
/* 给多肉写个程序:
1.属性: 名字、品种、高度、年龄;
2.行为: 浇水、晒太阳、说话(报告自己属性)
*/
public class Tree {
private String name;
private String breed;
private String colour;
private double high;
private int ageDay;
public Tree() {
}
public Tree(String name, String breed, String colour, double high, int ageDay) {
this.name = name;
this.breed = breed;
this.colour = colour;
this.high = high;
this.ageDay = ageDay;
}
public void speak(Tree tree){//说话问好
System.out.println("你好,我叫"+name+"是一株"+breed+"多肉。现在已经长了"+ageDay+"天了。有"+high+"cm高。请好好养我哦!");
System.out.println("你可以为我浇水或者晒太阳");
}
public void water(int a){
switch (a) {
case 1:
System.out.println("我快渴死了,快给我水喝。。。");
break;
case 2:
System.out.println("不渴不渴,你不用浇水了。。");
break;
case 3:
System.out.println("嗯,有点渴。你洒点水吧(*^▽^*)");
break;
default:
System.out.println("你昨天刚浇过啊,会把我淹死的!");
break;
}
}
public void bask(int b){
switch(b){
case 1:
System.out.println("好啊,今天太阳真好,把我放到阳台吧。");
break;
case 2:
System.out.println("不要晒了,今天太阳太热了。");
break;
case 3:
System.out.println("今天是雨天啊,晒什么太阳!");
break;
default:
System.out.println("好啊,你记得要把我拿回来啊");
break;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public double getHigh() {
return high;
}
public void setHigh(double high) {
this.high = high;
}
public int getAgeDay() {
return ageDay;
}
public void setAgeDay(int ageDay) {
this.ageDay = ageDay;
}
}
[Java] 纯文本查看 复制代码 package tree;
//调用Tree类 输出问候语
import java.util.Random;
import java.util.Scanner;
public class MyTree {
public static void main(String[] args) {
Tree treeOne = myTree();
treeOne.speak(treeOne);
System.out.println("浇水,晒太阳");
Scanner scan = new Scanner(System.in);
Random ran = new Random();
for (int i = 0; i < 3; i++) {
int numWater = ran.nextInt(4);
int numBask = ran.nextInt(6);
System.out.println("输入你想做的事");
String str1 = scan.next();
if ("浇水".equals(str1)) {
water(treeOne, numWater);//调用第一个方法
} else if ("晒太阳".equals(str1)) {
bask(treeOne, numBask);//调用第二个方法
} else {
System.out.println("输入错误");
}
}
}
public static Tree myTree(){
Tree myTree = new Tree();
myTree.setName("参天大树");
myTree.setBreed("白熊");
myTree.setColour("栗色");
myTree.setHigh(3.7);
myTree.setAgeDay(8);
return myTree;
}
public static void water(Tree treeOne,int numWater) {
treeOne.water(numWater);
}
public static void bask(Tree treeOne,int numBask) {
treeOne.bask(numBask);
}
} |