「java中校验纯数字」java 校验数字
本篇文章给大家谈谈java中校验纯数字,以及java 校验数字对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
java验证字符串是否为数字
java中判断字符串是否为纯数字的方法如下:
方法一:Pattern语句
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Testone {
public static void main(String[ ] args){
String str="123456";
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher((CharSequence)str);
boolean result=matcher.matches();
if (result == true) {
System.out.println("该字符串是纯数字");
}
else{
System.out.println("该字符串不是纯数字");
}
}
}
方法二:正则表达式
public static boolean isNumber(String str){
String reg = "^[0-9]+(.[0-9]+)?$";
return str.matches(reg);
}
Java 中怎样判断一个字符串全是数字
Java中判断字符串是否全是数字:
可以使用正则表达式:
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
但是这个方法并不安全,没有对字符串进行空校验。
在程序执行的时候很容易抛出异常。
例如执行:
public static void main(String[] args) {
String str = null;
System.out.println(BarcodeChecksum.INSTANCE.isNumeric(str));
}
就会抛出异常:
Exception in thread "main" java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1140)
at java.util.regex.Matcher.reset(Matcher.java:291)
at java.util.regex.Matcher.init(Matcher.java:211)
at java.util.regex.Pattern.matcher(Pattern.java:888)
at com.ossez.bcu.util.BarcodeChecksum.isNumeric(BarcodeChecksum.java:37)
at com.ossez.bcu.util.BarcodeChecksum.main(BarcodeChecksum.java:53)
所以这个方法并不准确。
如果执行:
public static void main(String[] args) {
String str = "";
System.out.println(BarcodeChecksum.INSTANCE.isNumeric(str));
}
将会返回 true。
这说明这个方法没有对空字符串进行校验。
可以使用 Apache 的 StringUtils.isNumeric() 函数进行判断。
这个函数位于 org.apache.commons.lang.StringUtils; 中。
但是,需要注意,如果传入参数为 "" 同样也会你存在判断不准确的情况,这时候需要首先对需要进行判断的参数进行非空校验,然后删除传入数据中的空格。
public static void main(String[] args) {
String str = "";
System.out.println(StringUtils.isNumeric(str));
}
上面这个函数将会返回 true。
请先 trim 数据
java中判断字符串是否为纯数字
方法一:利用正则表达式 public class Testone { public static void main(String[] args){ String str="123456"; boolean result=str.matches("[0-9]+"); if (result == true) { System.out.println("该字符串是纯数字");}else{System.out.println("该字符串不是纯数字");}}}方法二:利用Pattern. import java.util.regex.Matcher; import java.util.regex.Pattern; public class Testone { public static void main(String[] args){ String str="123456"; Pattern pattern = Pattern.compile("[0-9]{1,}"); Matcher matcher = pattern.matcher((CharSequence)str); boolean result=matcher.matches(); System.out.println("该字符串是纯数字");}else{System.out.println("该字符串不是纯数字");}}}
关于java中校验纯数字和java 校验数字的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。