简体   繁体   English

Setter 和 Getter

[英]Setter and Getter

So I was trying to make a Ride system just similar to that of uber.所以我试图制作一个类似于 uber 的 Ride 系统。 So I was trying to set some rules regarding the registration number of the car.所以我试图制定一些关于汽车注册号的规则。

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.";
        }
    }

According to this setter method, the registration number must be at least 6 characters long, the first three characters must be letters and the last three characters must be integers.根据这种setter方法,注册号必须至少有6个字符长,前三个字符必须是字母,后三个字符必须是整数。 Then I made a getter method and finally passed this registration number into a constructor of car class.然后我做了一个getter方法,最后把这个注册号传给了car类的一个构造函数。 But surprisingly when I am trying to print the registration number it is not obeying these rules.但令人惊讶的是,当我尝试打印注册号时,它并没有遵守这些规则。 I have added a picture of the result which I am getting.我已经添加了我得到的结果的图片。 enter image description here在此处输入图片说明

So if anyone knows why is this happening please let me know.所以如果有人知道为什么会这样,请告诉我。

You need delete from constructor parameter regNo and set this parameter using setter.您需要从构造函数参数regNo删除并使用 setter 设置此参数。 Something like this:像这样的东西:

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

Another way - you can use your setter in constructor for example:另一种方式 - 您可以在构造函数中使用您的 setter,例如:

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

The problem is that you don't use the setter method you have implemented to set regNo of your car.问题是您没有使用已实现的 setter 方法来设置汽车的regNo You should use that setter method in your constructor method to reuse the code you have written.您应该在构造函数方法中使用该 setter 方法来重用您编写的代码。 One other thing is that you should use regexes to check that it is in the form you want or not.另一件事是您应该使用正则表达式来检查它是否是您想要的形式。 Fallowing regex checks if the first three chars are "word character" and the next three are numbers: Fallowing regex 检查前三个字符是否为“单词字符”,接下来的三个字符是否为数字:

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!!!")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM