I'm trying to write a program that will score the Keirsey Bates personality test. The user passes a string that's 70 characters long and the string is evaluated based on the scoring method here.
I've written the program and everything works, but I know that it's not the most efficient/elegant way to do this. What I did was use 4 separate for loops to calculate the number of 'A's and 'B's in each column (for all columns except the first one, I used a nested for loop because I needed to add two columns together). For class standards, our method cannot exceed 50 LOC and our complete program (without the unit tests) must not exceed 100 LOC; repetition in code is also not allowed.
In my code I can see that there's a lot of repetition/similarity with the for loops and if/else statements. But I can't seem to think of a cleaner way to solve the problem. If someone could point me in the right direction, that would be awesome!
Here is the program I've written:
public class KeirseyScorer {
public static String evaluateSurvey(String responses) {
int surveyLength = 70;
String first = "", second = "", third = "", result = "";
int numAFirst = 0, numBFirst = 0, numASecond = 0, numBSecond = 0, numAThird = 0, numBThird = 0, numALast = 0, numBLast = 0;
if(responses.length() != surveyLength || !responses.matches("[AB]*")) {
result = "ERR!";
}
else {
//Gets first letter in personality type
for(int i = 0; i < surveyLength; i+= 7) {
if(responses.charAt(i) == 'A') {
numAFirst++;
}
else {
numBFirst++;
}
}
if(numAFirst > numBFirst) {
first = "E";
}
else if(numAFirst == numBFirst) {
first = "X";
}
else {
first = "I";
}
//Gets second letter in personality type
for(int j = 2; j < surveyLength; j+= 7) {
for(int k = 1; k < surveyLength; k += 7) {
if(responses.charAt(k) == 'A') {
numASecond++;
}
else {
numBSecond++;
}
}
}
if(numASecond > numBSecond) {
second = "S";
}
else if(numASecond == numBSecond) {
second = "X";
}
else {
second = "N";
}
//Gets third letter in personality type
for(int m = 4; m < surveyLength; m+= 7) {
for(int l = 3; l < surveyLength; l += 7) {
if(responses.charAt(l) == 'A') {
numAThird++;
}
else {
numBThird++;
}
}
}
if(numAThird > numBThird) {
third = "T";
}
else if(numASecond == numBSecond) {
third = "X";
}
else {
third = "F";
}
//Gets last letter and concats everything together for personality
for(int o = 6; o < surveyLength; o+= 7) {
for(int n = 5; n < surveyLength; n += 7) {
if(responses.charAt(n) == 'A') {
numALast++;
}
else {
numBLast++;
}
}
}
if(numALast > numBLast) {
result = first + second + third + "J";
}
else if(numALast == numBLast) {
result = first + second + third + "X";
}
else {
result = first + second + third + "P";
}
}
return result;
}
}
Aucun commentaire:
Enregistrer un commentaire