如何写一个包含基本属性name、age、gender、partner的Person类?
package first;
import java.util.Scanner;
public class first {
public static void main(String argsp[]){
int age[]=new int[2],i;
String name[]=new String[2],gender[]=new String[2],partnerName[]=new String[2];
try{
Scanner s = new Scanner(System.in);
for(i=0;i<2;i++){
System.out.println("请按顺序输入一个人名字、年龄、性别(男 or 女)和伴侣姓名(单身)");
System.out.println("姓名");
name[i] = s.nextLine();
System.out.println("年龄");
age[i] = Integer.parseInt(s.nextLine());
System.out.println("性别");
gender[i] = s.nextLine();
System.out.println("是否单身(没有就填单身)");
partnerName[i] = s.nextLine();}
//创建新的Person对象
Person one = new Person(name[0], age[0], gender[0], partnerName[0]);
Person two = new Person(name[1], age[1], gender[1], partnerName[1]);
switch(one.marry(two)){
case 1: //若返回值为true设置伴侣
one.setPartner(two);
System.out.println("可以结婚");
//以下下两句输出该人姓名和该人的伴侣
System.out.println(one.getName() + " 有和" + one.getPartner().getName()+"结婚的可能");
break;
case 0:
System.out.println("触犯重婚罪");
break;
case 2:
System.out.println("两人同性");
break;
case 3:
System.out.println("年龄不符");
}
}catch (Exception e){
System.out.println("输入格式或内容不正确");
}
}
}
class Person{
String name;
int age;
String gender;
Person partner;
//构造方法
Person(){
}
//构造方法
Person(String name, int age, String gender, String partnerName ){
this.name = name;
this.age = age;
this.gender = gender;
if(partnerName.equalsIgnoreCase("单身")){
this.partner = null;
}
else {
this.partner = new Person();
this.partner.name = partnerName;
}
}
//返回true的条件:不能重婚,不能是gay,男大于23,女大于21
public int marry(Person partner){
//判断是否已婚
if((this.getPartner() == null) && (partner.getPartner() == null)){
//判断双方性别
if( ! this.getGender().equalsIgnoreCase(partner.getGender())){
//判断男方岁数
if((partner.getGender().equalsIgnoreCase("男")&& partner.getAge()>=23)
|| (this.getGender().equalsIgnoreCase("男") &&this.getAge()>=23)){
//判断女方岁数
if((partner.getGender().equalsIgnoreCase("女")&& partner.getAge()>=21)
|| (this.getGender().equalsIgnoreCase("女") &&this.getAge()>=21)){
return 1;
}
return 2;
}
return 2;
}
return 3;
}
return 0;
}
//设置伴侣
public void setPartner(Person p){
this.partner = p;
p.partner = this;
}
//获得年龄
public int getAge(){
return this.age;
}
//获得性别
public String getGender(){
return this.gender;
}
//得到姓名
public String getName(){
return this.name;
}
//得到伴侣对象
public Person getPartner(){
if(this.partner != null){
return this.partner;
}
else return null;
}
}