Java如何检查字符串是否为有效数字?

在创建程序时,我们将使用很多字符串来表示我们的数据。数据可能不仅包含有关我们的客户名称,电子邮件或地址的信息,而且还将包含表示为字符串的数字数据。那么我们如何知道该字符串是否包含有效数字呢?

Java为原始数据类型提供了一些包装,可用于进行检查。这些包装附带的parseXXX()方法诸如Integer.parseInt(),Float.parseFloat()和Double.parseDouble()方法。

package org.nhooo.example.lang;

public class NumericParsingExample {
    public static void main(String[] args) {
        String age = "15";
        String height = "160.5";
        String weight = "55.9";

        try {
            int theAge = Integer.parseInt(age);
            float theHeight = Float.parseFloat(height);
            double theWeight = Double.parseDouble(weight);

            System.out.println("Age    = " + theAge);
            System.out.println("Height = " + theHeight);
            System.out.println("Weight = " + theWeight);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

在示例代码中我们使用Integer.parseInt(),Float.parseFloat(),Double.parseDouble()方法来检查我们的数字数据的有效性。如果字符串不是有效数字,java.lang.NumberFormatException将抛出该数字。

我们的示例的结果:

Age    = 15
Height = 160.5
Weight = 55.9