Home  >  Article  >  Java  >  How to determine whether a character is a number in java

How to determine whether a character is a number in java

尚
Original
2019-12-03 13:18:2114932browse

How to determine whether a character is a number in java

Java method to determine whether a character is a number: (Recommended: java video tutorial)

1. Use Character.isDigit(char) to determine

char num[] = str.toCharArray();//把字符串转换为字符数组
StringBuffer title = new StringBuffer();//使用StringBuffer类,把非数字放到title中
StringBuffer hire = new StringBuffer();//把数字放到hire中
for (int i = 0; i < num.length; i++) {
// 判断输入的数字是否为数字还是字符
if (Character.isDigit(num[i])) {把字符串转换为字符,再调用Character.isDigit(char)方法判断是否是数字,是返回True,否则False
hire.append(num[i]);// 如果输入的是数字,把它赋给hire} else {title.append(num[i]);// 如果输入的是字符,把它赋给title}}}

2. Use type conversion to judge

try {String str="123abc";

int num=Integer.valueOf(str);//把字符串强制转换为数字
return true;//如果是数字,返回True
} catch (Exception e) {
return false;//如果抛出异常,返回False}

3. Use regular expressions to judge

String str = "";
boolean isNum = str.matches("[0-9]+");
//+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")

For more java knowledge, please pay attention to the java basic tutorial column .

The above is the detailed content of How to determine whether a character is a number in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is java map?Next article:What is java map?