在解析字符串之前,如何检查它是否是一个数字?


当前回答

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        boolean flag = true;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the String:");
        String str = sc.nextLine();

        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) > 48 && str.charAt(i) < 58) {
                flag = false;
                break;
            }
        }

        if(flag == true) {
            System.out.println("String is a valid String.");
        } else {
            System.out.println("String contains number.");
        }
    }
}

其他回答

不要使用异常来验证你的值。 使用Util库代替apache NumberUtils:

NumberUtils.isNumber(myStringValue);

编辑:

请注意,如果字符串以0开头,NumberUtils将把您的值解释为十六进制。

NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false

Java 8 lambda表达式。

String someString = "123123";
boolean isNumeric = someString.chars().allMatch( Character::isDigit );

下面是用于检查字符串是否为数字的类。它还修复数值字符串:

特点:

删除不必要的零["12.0000000" -> "12"] 删除不必要的零["12.0580000" -> "12.058"] 删除非数字字符["12.00sdfsdf00" -> "12"] 处理负字符串值["-12,020000" -> "-12.02"] 删除多个点["-12.0.20.000" -> "-12.02"] 没有额外的库,只有标准Java

给你…

public class NumUtils {
    /**
     * Transforms a string to an integer. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToInteger(String str) {
        String s = str;
        double d;
        d = Double.parseDouble(makeToDouble(s));
        int i = (int) (d + 0.5D);
        String retStr = String.valueOf(i);
        System.out.printf(retStr + "   ");
        return retStr;
    }

    /**
     * Transforms a string to an double. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToDouble(String str) {

        Boolean dotWasFound = false;
        String orgStr = str;
        String retStr;
        int firstDotPos = 0;
        Boolean negative = false;

        //check if str is null
        if(str.length()==0){
            str="0";
        }

        //check if first sign is "-"
        if (str.charAt(0) == '-') {
            negative = true;
        }

        //check if str containg any number or else set the string to '0'
        if (!str.matches(".*\\d+.*")) {
            str = "0";
        }

        //Replace ',' with '.'  (for some european users who use the ',' as decimal separator)
        str = str.replaceAll(",", ".");
        str = str.replaceAll("[^\\d.]", "");

        //Removes the any second dots
        for (int i_char = 0; i_char < str.length(); i_char++) {
            if (str.charAt(i_char) == '.') {
                dotWasFound = true;
                firstDotPos = i_char;
                break;
            }
        }
        if (dotWasFound) {
            String befDot = str.substring(0, firstDotPos + 1);
            String aftDot = str.substring(firstDotPos + 1, str.length());
            aftDot = aftDot.replaceAll("\\.", "");
            str = befDot + aftDot;
        }

        //Removes zeros from the begining
        double uglyMethod = Double.parseDouble(str);
        str = String.valueOf(uglyMethod);

        //Removes the .0
        str = str.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");

        retStr = str;

        if (negative) {
            retStr = "-"+retStr;
        }

        return retStr;

    }

    static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

}

这就是为什么我喜欢。net中的Try*方法。除了像Java一样的传统Parse方法之外,还有一个TryParse方法。我不擅长Java语法(输出参数?),所以请将以下内容视为某种伪代码。但它应该让概念变得清晰。

boolean parseInteger(String s, out int number)
{
    try {
        number = Integer.parseInt(myString);
        return true;
    } catch(NumberFormatException e) {
        return false;
    }
}

用法:

int num;
if (parseInteger("23", out num)) {
    // Do something with num.
}
private static Pattern p = Pattern.compile("^[0-9]*$");

public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    return p.matcher(strNum).find();
}