JAVA课堂作业,本人才上了一节课就要做了,需要用JAVA实现家谱,求大神援手【泪目】
3条回答 默认 最新
- qfl_sdu 2021-09-13 11:28关注
代码如下:
(1)新建一个Person类public class Person { protected String name; protected int age; protected Person father; protected Person mother; protected Person[] child; Person(){ father = null; mother = null; child = null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person getFather() { return father; } public void setFather(Person father) { this.father = father; } public Person getMother() { return mother; } public void setMother(Person mother) { this.mother = mother; } public Person[] getChild() { return child; } public void setChild(Person[] child) { this.child = new Person[child.length]; for(int i = 0;i<child.length;i++){ this.child[i] = child[i]; } } public void Said(){ System.out.print("我的名字是" + name ); if(father != null) System.out.print(",我的父亲是" + father.getName()); if(mother != null) System.out.print(",母亲是"+mother.getName()); if(this.child != null){ if(this.child.length > 0){ System.out.print(",我有" + this.child.length + "个孩子。"); System.out.print("分别是:"); for(int i = 0;i<this.child.length; i++) System.out.print(" " + this.child[i].getName()); } }else System.out.print(",我没有孩子"); System.out.println(); } }
(2)添加一个测试类:
public class TestWork { public static void main(String[] args){ Person p1 = new Person(); p1.setName("张翠山"); p1.setAge(56); Person p2 = new Person(); p2.setName("殷素素"); p2.setAge(54); Person p3 = new Person(); p3.setName("张无忌"); p3.setAge(28); Person p4 = new Person(); p4.setName("无名氏"); p4.setAge(22); Person[] ch = new Person[2]; ch[0] = p3; ch[1] = p4; p1.setChild(ch); p2.setChild(ch); p3.setFather(p1); p3.setMother(p2); p4.setFather(p1); p4.setMother(p2); p1.Said(); p2.Said(); p3.Said(); p4.Said(); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用 2
悬赏问题
- ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
- ¥15 Vue3地图和异步函数使用
- ¥15 C++ yoloV5改写遇到的问题
- ¥20 win11修改中文用户名路径
- ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
- ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
- ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
- ¥15 帮我写一个c++工程
- ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
- ¥15 关于smbclient 库的使用