-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnector.java
110 lines (92 loc) · 2.33 KB
/
Connector.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
102
103
104
105
106
107
108
109
110
public class Connector {
// Implement an immutable connector that connects two points on the game board.
// Invariant: 1 <= myPoint1 < myPoint2 <= 6.
private int myPoint1, myPoint2;
public Connector (int p1, int p2) {
if (p1 < p2) {
myPoint1 = p1;
myPoint2 = p2;
} else {
myPoint1 = p2;
myPoint2 = p1;
}
}
public int endPt1 ( ) {
return myPoint1;
}
public int endPt2 ( ) {
return myPoint2;
}
public boolean equals (Object obj) {
Connector e = (Connector) obj;
return (e.myPoint1 == myPoint1 && e.myPoint2 == myPoint2);
}
public String toString ( ) {
return "" + myPoint1 + myPoint2;
}
public boolean isOK()
{
if (myPoint1 == myPoint2)
return false;
if (myPoint1 < 1 || myPoint1 > 6 || myPoint2 < 1 || myPoint2 > 6)
return false;
return true;
}
public int hashCode()
{
return myPoint1 ^ myPoint2;
}
// Format of a connector is endPoint1 + endPoint2 (+ means string concatenation),
// possibly surrounded by white space. Each endpoint is a digit between
// 1 and 6, inclusive; moreover, the endpoints aren't identical.
// If the contents of the given string is correctly formatted,
// return the corresponding connector. Otherwise, throw IllegalFormatException.
public static Connector toConnector (String s) throws IllegalFormatException
{
if (s == null)
throw new IllegalFormatException("Null string");
else if (s.length() <= 1)
throw new IllegalFormatException("String with length <= 1");
int p1, p2;
p1 = p2 = 0;
boolean found_number = false;
int i, numcount;
i = numcount = 0;
while (i < s.length())
{
if(Character.isWhitespace(s.charAt(i)))
{
if(found_number)
{
throw new IllegalFormatException("Whitespace between endpoints");
}
}
else
{
if(s.charAt(i) < '1' || s.charAt(i) > '6')
throw new IllegalFormatException("Not an endpoint");
else
{
++numcount;
if(numcount == 1)
{
p1 = s.charAt(i) - '0';
found_number = true;
}
else if(numcount == 2)
{
p2 = s.charAt(i) - '0';
found_number = false;
}
else
throw new IllegalFormatException("More than 2 endpoints found"); //more than 2 endpoints
}
}
++i;
}
if(p1 != p2)
return new Connector(p1,p2);
else
throw new IllegalFormatException("Endpoints are the same");
}
}