-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFeedback.java
More file actions
110 lines (97 loc) · 2.83 KB
/
Feedback.java
File metadata and controls
110 lines (97 loc) · 2.83 KB
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
import java.util.*;
public class Feedback
{
//instance variables
String feedback;
public Feedback()
{
feedback = "";
}
public boolean getFeedback(Code comp, Code user)
{
if(comp == null || user == null)
{
throw new IllegalArgumentException("Violation of precondition:" +
" comp must not be null and user must not be null.");
}
feedback = "";
char black = 'B';
char white = 'W';
Peg[] userCode = new Peg[comp.size()];
Peg[] compCode = new Peg[comp.size()];
for(int i = 0; i < comp.size(); i++)
{
userCode[i] = user.getPeg(i);
compCode[i] = comp.getPeg(i);
}
int maxSize = comp.size();
//first we will iterate and check for black
//once compared set the code array element to null,
//to avoid double match of colors
for(int i = 0; i < maxSize; i++)
{
//first checks if the position and color are the same
if(compCode[i].equals(userCode[i]))
{
feedback += black;
compCode[i] = null;
userCode[i] = null;
}
}
//now, iterate again and check for white
for(int i = 0; i < maxSize; i++)
{
for(int j = 0; j < maxSize; j++)
{
//checks if the color is the same, but position
//is different
if(compCode[i] != null && userCode[j] != null)
{
if(compCode[i].equals(userCode[j]))
{
feedback += white;
compCode[i] = null;
userCode[j] = null;
}
}
}
}
//method returns true if the user wins and false otherwise
if(comp.equals(user))
{
return true;
}
else
{
return false;
}
}
// adds all the Blacks to the string, then all of the Whites
// then returns the string
public String toString()
{
String str = "";
if(feedback.length() == 0)
{
str += "No pegs";
}
else
{
for(int i = 0; i < feedback.length(); i++)
{
if(feedback.charAt(i) == 'B')
{
str += "Black ";
}
}
for(int i = 0; i < feedback.length(); i++)
{
if(feedback.charAt(i) == 'W')
{
str += "White ";
}
}
}
return str;
}
}