当前位置: 移动技术网 > IT编程>开发语言>Java > Java判断字符串为空、字符串是否为数字

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

夏增文,梅花5角硬币,恶少相公你给我趴下

关于 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;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网