塞特和吸气剂

问题描述

所以我试图制作一个与uber类似的Ride系统。所以我试图为汽车的注册号制定一些规则。

public void setRegNo(String regNo) {
        if (regNo.length() == 6) {
            if (regNo.substring(0,3).matches("[a-zA-Z]+")) {
                if (regNo.substring(3).matches("[0-9]+")) {
                    this.regNo = regNo;
                } else {
                    this.regNo = "Error! The Registration number ends with 3 numerical characters.";
                }
            } else {
                this.regNo = "Error! The registration number begins with 3 alphabetical characters.";
            }
        } else {
            this.regNo = "Error! The Registration number must be 6 characters long.";
        }
    }

根据此setter方法注册号必须至少为6个字符长,前三个字符必须为字母,后三个字符必须为整数。然后,我做了一个getter方法,最后将此注册号传递给了car类的构造函数。但是令人惊讶的是,当我尝试打印注册号时,它没有遵守这些规则。我已经添加了我得到的结果的图片enter image description here

所以如果有人知道为什么会这样,请告诉我。

解决方法

您需要从构造函数参数regNo中删除并使用setter设置此参数。像这样:

Car car = new Car("cat","dog","pranav Khurana",4);
car.setRegNo("abc3");

另一种方法-例如,您可以在构造函数中使用setter:

public Car(String regNo,String name) {
    this.setRegNo(regNo);
    this.name = name;
}
,

问题是您没有使用已实现的setter方法来设置汽车的regNo。您应该在构造函数方法中使用该setter方法来重用您编写的代码。另一件事是,您应该使用正则表达式来检查它是否符合您想要的形式。常规正则表达式检查前三个字符是否为“单词字符”,后三个字符是否为数字:

public void setRegNo(String regNo) {
    String myRegex="\\w\\w\\w\\d\\d\\d";
    if (regNo.matches(myRegex))
        this.regNo=regNo;
    else
        System.err.println("This is not a  registration number!!!")
}