Home > Java > JavaBase > Java method to determine whether string is a number

Java method to determine whether string is a number

Release: 2019-12-27 14:50:58
Original
13672 people have browsed it

Java method to determine whether string is a number

Method to determine whether a string is a number in java:

1. Use JAVA’s own function

public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
Copy after login

charAt() method for Returns the character at the specified index. The index range is from 0 to length() - 1.

Syntax

public char charAt(int index)
Copy after login

Parameters: index -- The index of the character.

Return value: Returns the character at the specified index.

isDigit() method is used to determine whether the specified character is a number.

Syntax: public static boolean isDigit(char ch)

Parameters: ch -- The character to be tested.

Return value: If the character is a number, return true; otherwise, return false.

2. Use regular expressions

First import java.util.regex.Pattern and java.util.regex.Matcher

public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
Copy after login

3. Use org .apache.commons.lang

org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
Copy after login

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

The above is the detailed content of Java method to determine whether string is a number. 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