检查字符串是否为0到99之间的数字

时间:2013-10-21 23:53:54

标签: java

public class raceCar{
    private String driver;
    private String car;

    public raceCar(String driver, String car){
        this.driver = driver;
        this.car = car;
    }
}

我需要在构造函数中传入两个字符串,但构造函数需要检查字符串是否为0到99之间的数字,如果不是,则将其设置为“00”。

3 个答案:

答案 0 :(得分:3)

要测试,请使用正则表达式:

if (str.matches("[1-9]?\\d")) {
    // it's a number between 0 and 99
}

这可以通过使用regular expression来检查字符串。表达式的部分是:

  • [1-9]? 1到9范围内的单个字符,?
  • 可选
  • \d任意数字

正则表达式可能是\d\d,但这样就可以使用“00”。

仅供参考,在java String.matches()中,如果整个字符串与模式匹配,则仅返回true,因此不需要^和$。这与许多其他语言不同,它们在部分匹配时返回true。

答案 1 :(得分:2)

您可以使用int将字符串转换为Integer.parseInt(),然后使用if语句检查它是否大于-1且小于100.

答案 2 :(得分:0)

public class raceCar
{
    private String driver;
    private String car;

    public raceCar(String driver, String car)
    {
        if (Integer.parseInt(driver) < 100 && Integer.parseInt(driver) >= 0)
            this.driver = driver;
        else
            this.driver = "00";

        if (Integer.parseInt(car) < 100 && Integer.parseInt(car) >= 0)
            this.car = car;
        else
            this.car = "00";
    }