forked from XINLA9/COMP1110-Exam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q5Monarch.java
101 lines (87 loc) · 2.84 KB
/
Q5Monarch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package comp1110.exam;
import java.util.Objects;
import java.util.Random;
/**
* COMP1110 Final Exam, Question 5
*
* This class represents a monarch (a king or queen), who is uniquely
* identified by a combination of first name, number, and country, for example:
* {"Edward",7,"United Kingdom"} or {"Catherine,2,Russia"}.
*
* A monarch may also have a cognomen (nickname), which is not part of their
* unique identity.
* For example: {"Edward",1,"England"} with the cognomen "Longshanks" and
* {"Edward",1,"England"} with the cognomen "the Hammer of the Scots" are the
* same person, even though the cognomen is different.
*/
public class Q5Monarch {
/**
* The name of this monarch e.g. "Elizabeth".
*/
String name;
/**
* The number of this monarch e.g. 1.
*/
int number;
/**
* The country of this monarch e.g. "United Kingdom".
*/
String country;
/**
* The cognomen of this monarch e.g. "the Glorious".
* Does not form part of this monarch's unique identity.
*/
String cognomen;
public Q5Monarch(String name, int number, String country, String cognomen) {
this.name = name;
this.number = number;
this.country = country;
this.cognomen = cognomen;
}
/**
* @return a hash code value for this monarch
* In implementing this method, you may *not* use the default Java
* implementations in Object.hashCode() or Objects.hash().
* @see Object#hashCode()
*/
@Override
public int hashCode() {
// FIXME complete this method
String s = this.name+this.country;
Random ran =new Random(s.length());
int sum=0;
for (char c: s.toCharArray()){
sum=sum+ran.nextInt(c);
}
sum=sum+this.number*2;
return sum%50;
//return new Random().nextInt(1000);
}
/**
* @return true if this monarch is equal to the provided object
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
// FIXME complete this method
if (object==null) return false;
if (object==this) return true;
if(!(object instanceof Q5Monarch)) return false;
Q5Monarch given = (Q5Monarch) object;
return Objects.equals(this.name,given.name)&& Objects.equals(this.country,given.country)&&this.number==given.number;
//return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name).append(" ")
.append(number).append(" of ")
.append(country);
if (cognomen != null && !cognomen.isEmpty()) sb.append(" \"").append(cognomen).append("\"");
return sb.toString();
}
// DO NOT DELETE OR CALL THIS METHOD
int passThroughHash() {
return super.hashCode();
}
}