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

Java method to determine whether string is a number

尚
Original
2019-12-27 14:50:5813700browse

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;
}

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)

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;
}

3. Use org .apache.commons.lang

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

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!

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