在java中检查空字符串

时间:2014-12-24 09:16:50

标签: java

我有一个带有以下程序的数组超出绑定异常。问题来自于我的第一个if语句(expression == "")没有捕获我的表达式为空的情况。为什么没有捕获,我怎样才能正确地写出这个条件?

  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);
    }
  }

1 个答案:

答案 0 :(得分:1)

isEmpty字符串有默认方法。

if (expression.isEmpty())

而不是

if (expression == "")