In this method, I'm trying to go through a string of 70 characters until I reach a letter that's not an 'A' or a 'B'. Once I find a character that doesn't belong, I should return "ERR!"; I also return this statement if the string is not exactly 70 characters long.
The way I did it was by keeping track of both the total letters counted so far, and the total number of wrong letters (letters not 'A' or 'B'). Then I said that if the number of wrong letters was not 0 and if the length of the string came out to be not 70, the "ERR!" message is returned.
public static String checkInput(String answers) {
int count = 0;
int wrong = 0;
String errorMessage = "";
for(int i = 0; i < answers.length(); i++) {
count++;
if(answers.charAt(i) != 'A' && answers.charAt(i) != 'B') {
wrong++;
}
}
if(wrong != 0 || count != ANSWER_LENGTH) {
errorMessage = "ERR!";
}
return errorMessage;
}
My code works perfectly fine, but if there is anything that can be shortened or simplified to reduce the number of lines in my program, that's what I need. Any ideas/tips are appreciated!!
Aucun commentaire:
Enregistrer un commentaire