Home > Java > javaTutorial > How to determine whether a string is a number in java?

How to determine whether a string is a number in java?

青灯夜游
Release: 2019-11-20 11:53:54
Original
6889 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 a string is a number in java?

#How does Java determine whether a string is a number?

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

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 judge

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

3 , Use Pattern class and Matcher to judge

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 a string 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