This is my professor's assignment for oo programming. But I found that the marital status can be an variable in the Person class, how can I achieve this with two classes?
Assume people can have marital status: single, married, widow, divorced. Create a state OODP (i.e., Java, JavaScript, C++, Python, or Ruby) that deal with people's marital status. You will have at least two classes: Person, and Marital State. Make sure the following rules are followed: single->married married-> divorced | widow divorced -> married widow -> married create a Client class to test your program. Make sure you test valid and invalid change of marital status.
The assignment page
These are my codes:
public class AssignmentOOP {
public static void main(String[] args) {
Person p1 = new Person("p1");
Person p2 = new Person("p2");
Person p3 = new Person("p3");
p1.PrintMaritalStatus();
p2.PrintMaritalStatus();
p3.PrintMaritalStatus();
p1.GetMarried(p2);
p1.GetMarried(p3);
p2.Died();
p1.GetMarried(p3);
}
}
class Person {
String maritalstatus;
boolean mateIsAlive;
Person mate;
String name;
Person(String name1) {
maritalstatus = "single";
mate = null;
name = name1;
}
void GetMarried(Person mate) {
if(this.maritalstatus.equals("married")|| mate.maritalstatus.equals("married"))
{
System.out.println("Marital status error! At least one of you are married");
return;
} else {
this.maritalstatus = "married";
this.mate = mate;
mate.maritalstatus = "married";
mate.mate = this;
System.out.println("Congratulations!!! " + this.name + " and " + mate.name + " are married!");
}
}
void GetDivorced(Person mate) {
if(this.maritalstatus.equals("married") && this.mate == mate) {
maritalstatus = "divorced";
System.out.println(this.name+" and "+mate.name+" are getting divorced.");
}else if(this.maritalstatus.equals("single")) {
System.out.println("You are not married and you cannot get divorced before getting married");
}else if(maritalstatus.equals("widow")) {
System.out.println("Your marital status is widow, you cannot get divorced.");
}
}
void Died() {
this.maritalstatus = "dead";
this.mate.maritalstatus = "widow";
System.out.println("Sorry for your loss, " + this.mate.name + " marital status is widow.");
}
void PrintMaritalStatus() {
System.out.println(this.name + " marital status is " + this.maritalstatus);
}
}
Aucun commentaire:
Enregistrer un commentaire