0

I have an array out of bound exception with the following program. The problem comes from the fact that my first if statement (expression == "") doesn't catch the case where my expression is empty. Why is it not catched and how can I properly write this condition?

  public static boolean isWellFormed(String expression, int braces, int brackets, int parentheses){
    if (expression == ""){
      if (braces == 0 && brackets == 0 && parentheses == 0){
        return true;
      }
      else{
        return false;
      }
    }
    System.out.println("expression " + expression + " " + expression.length());
    char firstChar = expression.charAt(0);
    if (firstChar == '['){
      return isWellFormed(expression.substring(1),braces, brackets+1, parentheses);
    }
    else if(firstChar == '{'){
      return isWellFormed(expression.substring(1),braces+1, brackets, parentheses);      
    }
    else if(firstChar == '('){
      return isWellFormed(expression.substring(1),braces, brackets, parentheses+1);
    }
    else if(firstChar == ']'){
      return isWellFormed(expression.substring(1),braces, brackets-1, parentheses);
    }
    else if(firstChar == '}'){
      return isWellFormed(expression.substring(1),braces-1, brackets, parentheses);
    }
    else if(firstChar == ')'){
      return isWellFormed(expression.substring(1),braces, brackets, parentheses-1);
    }  
    else{
      return isWellFormed(expression.substring(1),braces, brackets, parentheses);
    }
  }
giulio
  • 659
  • 2
  • 8
  • 22
  • In Java Strings should't be compared with the `==` Operator but with the method `.equals()` - But there is also a method called `isEmpty()` you could use. – dehlen Dec 24 '14 at 09:18

1 Answers1

1

isEmpty String having default method.

if (expression.isEmpty())

instead of

if (expression == "")
newuser
  • 8,338
  • 2
  • 25
  • 33