1. 编写两个宠物类(猫、狗),people类,人选择要喂养的宠物以及喂养的食物,判断该宠物是否喜欢吃这个食物,打印输出该宠物的信息
//创建一个猫类
public class Cat {
String name;
String type;
String[] food = {"鱼","猫粮"};
}
//创建一个狗类
public class Dog {
String name;
String type;
String[] food = {"骨头","狗粮"};
}
import java.util.Scanner;
//创建一个人类
public class People {
String name;
int age;
String sex;
Scanner sc = new Scanner(System.in);
public void message() {
System.out.println("姓名:"+name);
System.out.println("年龄:"+age);
System.out.println("性别:"+sex);
}
//喂养的方法
public void feed() {
System.out.print("请输入你要喂的宠物(猫、狗):");
String animal = sc.next();
System.out.print("请放入你要喂养的食物:");
String food1 = sc.next();
if("狗".equals(animal)) {
Dog dog = new Dog();
dog.name="汪汪";
dog.type="金毛";
System.out.println("狗的名字:"+dog.name);
System.out.println("狗的种类:"+dog.type);
String[] foodi = dog.food;
for (int i = 0; i < foodi.length; i++) {
if(food1.equals(foodi[i])) {
System.out.println("狗狗喜欢吃:"+food1);
break;
}else if(i==foodi.length-1){
System.out.println("狗狗不喜欢吃");
}
}
}else if("猫".equals(animal)) {
Cat cat = new Cat();
cat.name="喵喵";
cat.type="银渐层";
System.out.println("猫的名字:"+cat.name);
System.out.println("猫的种类:"+cat.type);
String[] foodi = cat.food;
for (int i = 0; i < foodi.length; i++) {
if(food1.equals(foodi[i])) {
System.out.println("猫猫喜欢吃:"+food1);
break;
}else if(i==foodi.length-1){
System.out.println("猫猫不喜欢吃");
}
}
}
}
}
//测试类
public class TestPeople {
public static void main(String[] args) {
People people = new People();
people.name="谭惠文";
people.age=21;
people.sex="女";
people.message();
people.feed();
}
}
姓名:张三
年龄:21
性别:女
请输入你要喂的宠物(猫、狗):狗
请放入你要喂养的食物:骨头
狗的名字:汪汪
狗的种类:金毛
狗狗喜欢吃:骨头
姓名:张三
年龄:21
性别:女
请输入你要喂的宠物(猫、狗):猫
请放入你要喂养的食物:骨头
猫的名字:喵喵
猫的种类:银渐层
猫猫不喜欢吃