Java中判断字符串是否为数字的几种方法

Python034

Java中判断字符串是否为数字的几种方法,第1张

1.使用Character.isDigit(char)判断char num[] = str.toCharArray()//把字符串转换为字符数组StringBuffer title = new StringBuffer()//使用StringBuffer类,把非数字放到title中StringBuffer hire = new StringBuffer()//把数字放到hire中for (int i = 0i <num.lengthi++) {// 判断输入的数字是否为数字还是字符if (Character.isDigit(num[i])) {把字符串转换为字符,再调用Character.isDigit(char)方法判断是否是数字,是返回True,否则Falsehire.append(num[i])// 如果输入的是数字,把它赋给hire} else {title.append(num[i])// 如果输入的是字符,把它赋给title}}}2.使用类型转换判断try {String str="123abc"int num=Integer.valueOf(str)//把字符串强制转换为数字return true//如果是数字,返回True} catch (Exception e) {return false//如果抛出异常,返回False}3.使用正则表达式判断String str = ""boolean isNum = str.matches("[0-9]+")//+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")ps:这个方法只能用于判断是否是正整数

import java.util.Scanner

import java.util.regex.Matcher

public class Test {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in)

String s = reader.next()

if (s.matches("[\\d]+[\\.]?[\\d]*")) {

System.out.println("是数字")

} else {

System.out.println("不是数字")

}

}

}