user2387766
user2387766

Reputation:

Is there a more efficient way to iterate through a string until you reach a certain character?

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!!

Upvotes: 0

Views: 1126

Answers (3)

sathya_dev
sathya_dev

Reputation: 513

This way if there are any characters other than A or B it would immediately fails.

public static final String checkInput(final String answers) {
    if (answers==null || answers.length() != ANSWER_LENGTH)
        return "ERR!"; // fail fast
    if(!answer.matches("[AB]*")) 
       return "ERR!"; // fail fast
    return "";
}

Upvotes: 2

Sammy
Sammy

Reputation: 477

I would add a null check to Lashane's answer for robustness.

if (answers == null || answers.length() != 70)

Upvotes: 2

Iłya Bursov
Iłya Bursov

Reputation: 24146

Number of lines (or lines of code LOC) is not very important in java, but anyway, here is shorter and faster variant:

public static final String checkInput(final String answers) {
    if (answers.length() != ANSWER_LENGTH)
        return "ERR!"; // fail fast
    for (int i = 0; i < answers.length(); i++)
        if (answers.charAt(i) != 'A' && answers.charAt(i) != 'B')
            return "ERR!"; // fail fast
    return "";
}

Upvotes: 1

Related Questions