search
HomeJavaJavaBaseJava method to determine whether string is a number

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)