Java判断字符串为空、字符串是否为数字


关于 String 的判空:

复制代码 代码如下:
//这是对的
if (selection != null && !selection.equals("")) {
      whereClause += selection;
  }

//这是错的
if (!selection.equals("") && selection != null) {
      whereClause += selection;
  }

注:“==”比较两个变量本身的值,即两个对象在内存中的首地址。而“equals()”比较字符串中所包含的内容是否相同。第二种写法中,一旦 selection 真的为 null,则在执行 equals 方法的时候会直接报空指针异常导致不再继续执行。

判断字符串是否为数字:

复制代码 代码如下:

// 调用java自带的函数
public static boolean isNumeric(String number) {
  for (int i = number.length(); --i >= 0;) {
      if (!Character.isDigit(number.charAt(i))) {
          return false;
      }
  }
  return true;
}

// 使用正则表达式
public static boolean isNumeric(String number) {
  Pattern pattern = Pattern.compile("[0-9]*");
  return pattern.matcher(str).matches();
}

// 利用ASCII码

public static boolean isNumeric(String number) {
  for (int i = str.length(); --i >= 0;) {
      int chr = str.charAt(i);
      if (chr < 48 || chr > 57)
          return false;
  }
  return true;
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3