vendredi 16 octobre 2020

Does order of the states in the if statement matter?

from line 5 on my code which is,

if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')

Does the order of statements matter? I was wondering because

when I assign str = "yak123ya"

(i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k') works perfectly fine but

(str.charAt(i) == 'y' && str.charAt(i + 2) == 'k' && i + 2 < str.length()) causes

error

StringIndexOutOfBoundsException: String index out of range: 8 (line:5)

public String stringYak(String str) {
  String result = "";

  for (int i = 0; i < str.length(); i++) {
    if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k') {
      i += 2;
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

Thank you!!

Aucun commentaire:

Enregistrer un commentaire