jeudi 29 octobre 2015

Java= arbitrary placement of if statement gives different output? [duplicate]

I am goofing around in CodingBat with Java Strings warm-ups.

The prompt was:

Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).

last2("hixxhi") → 1

last2("xaxxaxaxx") → 1

last2("axxxaaxx") → 2

My first attempt was:

public int last2(String str) {

   String last = str.substring(str.length()-2);
   int count = 0;

   if (str.length() < 2){
      return 0;
   }


   for (int i = 0; i <str.length()-2; i++){
      String sub = str.substring(i,i+2);

      if (sub.equals(last)){
         count++;
      }
    }

return count;

}

This code produced the correct output for all tests except when the input string had a length less than 2 (output = Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:3), etc.), meaning the if statement was ignored.

enter image description here

However, simply moving the if statement above the variable declarations in the beginning of the method made the code correctly pass all tests (even strings with length less than two):

public int last2(String str) {

   if (str.length() < 2){
     return 0;
   }

  String last = str.substring(str.length()-2);
  int count = 0;

  for (int i = 0; i <str.length()-2; i++){
      String sub = str.substring(i,i+2);

      if (sub.equals(last)){
        count++;
       }
    }

    return count;

  }

Output for attempt 1

I feel like the variable declarations shouldn't have any impact on the functionality of the if statement... what is keeping my first coding attempt from working?

Aucun commentaire:

Enregistrer un commentaire