Teach you step by step 5 ways to determine whether a string is a number in Java

Method 1: Use JAVA’s own function
public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i ))){
return false;
}
}
return true;
}

Method 1 traverses each character of the string and uses the Character.isDigit() function to check whether each character is a number. If all characters in the string are numbers, this method will return true . However, if the string contains non-numeric characters, it will immediately return false .

This approach is neat and tidy, but may be overly strict because it considers a string like "123" (which contains a space at the end) not to be a number.

 

Method 2:
/*
* Determine whether it is an integer

* @param str The string passed in
* @return is an integer and returns true, otherwise it returns false
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^ [-\+]?[\d]*$");
return pattern.matcher(str).matches();
}

Method 2 uses regular expressions to check whether the string contains only numbers. It matches all strings starting with the regular expression ["^[-+]?[\d]*$"] . This regular expression means that the beginning of the string can be a positive or negative sign, followed by any number of numbers. However, it thinks a string like "123" is an integer, when in fact "" is not part of a number.

 

Method three: FuncGPT (Hui function) automatically generates
package com.feisuanyz.function;

import com.feisuanyz.flow.core.cmpt.annotation.function.MethodDesc;

import com.feisuanyz.flow.core.cmpt.annotation.function.ParamDesc;

 

public class StringNumberChecker {

   

@MethodDesc (desc = " Determine whether the string is a number " ,

params = {

@ ParamDesc (name = "str" , desc = " String to be judged " ),

})

public static boolean isNumeric(String str) {

        if (str == null || str . isEmpty ()) { // Check whether the string is empty

            return false ;

        }

 

        try {

            Double .parseDouble (str); // Use the Double.parseDouble() method to try to convert the string to double

            return true ; // Conversion successful, the string is a number

        } catch (NumberFormatException e) {

            return false ; // Conversion failed, the string is not a number

        }

    }

}

Method three uses the Double.parseDouble() method to try to convert the string into a double-precision floating point number. If the conversion is successful, it means that the string is a number, and true is returned; if the conversion fails, it means that the string is not a number, and false is returned.

This code snippet includes an annotation @MethodDesc, which is used to describe some information about this method, including its description (desc) and parameters (params). The parameter description is also an array, where each element has a name (name) and description (desc). This kind of annotation is usually used to generate API documentation or for the code prompt function of some IDEs.

The design idea of ​​this isNumeric method is reasonable and can meet the needs of most scenarios. However, it is important to note that since the Double.parseDouble() method can parse a string such as "3.14" into a valid floating point number, the method may be somewhat loose with the definition of "number" in the strict sense. If you need a more precise definition (for example, only accepting integer values ​​or only floating point numbers with a specific number of decimal places), you may need to customize a more complex method to check the string.

Overall, this is a simple, clear way to efficiently check if a string can be parsed as a number.

 

方法四:
public final static boolean isNumeric(String s) {
if (s != null && !"".equals(s.trim()))
return s.matches("^[0-9]*$");
else
return false;
}

Method 4 first checks whether the string is empty or contains only spaces, and returns false if the condition is met . Then it uses String 's matches() method to check whether the string matches the regular expression "^[0-9]*$" . This regular expression means that the string consists only of numbers 0-9 . This method takes into account empty strings and spaces, but will still treat strings like "123" as numbers when encountered.


方法五:用ascii码
public static boolean isNumeric(String str){
for(int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
return true;
}

This method determines whether it is a number by checking the ASCII code of each character in the string. If the character's ASCII code is not between 48 ( '0' ) and 57 ( '9' ), it immediately returns false . This method is very concise, but also very strict, and will consider a string like "123" not to be a number, even though " " is part of a number.

 

In summary, each of these methods has its advantages and disadvantages, and which method you choose depends on your specific needs and your definition of " numbers . "

 

FuncGPT is the latest feature launched by the full-stack automatic development tool SoFlu software robot. It focuses on AI- generated Java functions, describes Java function requirements through natural language, and generates high-quality, highly readable Java function codes in real time. The generated code can be directly copied to IDEA , or imported into the Java fully automatic development tool function library with one click. Now available for free development and use, link:https://suo.im/aWkTE

Fined 200 yuan and more than 1 million yuan confiscated You Yuxi: The importance of high-quality Chinese documents Musk's hard-core migration server Solon for JDK 21, virtual threads are incredible! ! ! TCP congestion control saves the Internet Flutter for OpenHarmony is here The Linux kernel LTS period will be restored from 6 years to 2 years Go 1.22 will fix the for loop variable error Google celebrates its 25th anniversary Svelte has built a "new wheel" - runes
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4868096/blog/10112537