Home > Java > JavaBase > body text

How to determine whether it is a number in java

angryTom
Release: 2019-11-12 14:08:42
Original
4038 people have browsed it

When programming, we often encounter the need to determine whether the characters in a string are numbers (0-9) and whether the string is a number. You may use some of the methods that come with Java, or you may use other methods. Weird tricks, such as judging whether it is an integer number and forcing the string to be an integer. If it is not a number, an error will be thrown, so it is not an integer. Here I will introduce you to several implementation methods.

How to determine whether it is a number in java

How to judge whether it is a number in java

1. Use Character.isDigit(char) to judge (only one can be judged Characters)

String str = "123abc";
if (!"".equals(str)) {
    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
        }
    }
}
Copy after login

2. Use type conversion to determine

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

3. Use regular expressions to determine

String str = "";
boolean isNum = str.matches("[0-9]+");
//+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")  
4. 使用Pattern类和Matcher
view plaincopy
String str = "123";
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher((CharSequence) str);
boolean result = matcher.matches();
if (result) {
    System.out.println("true");
} else {
    System.out.println("false");
}
Copy after login

Recommended tutorial: java tutorial

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template