Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating if in setter/getter

Quite new with Java and wanted some help with storing passenger details whilst using setters/getters and creating an output with the toString method.

The problem I have is, say I am storing the passengers phone number and don't want their phone number to contain any characters, have a length of 10 numbers and start with 1 and return "Not Valid" if one of these occur.

I have tried to create if statements in the setter but it is not returning the "Not Valid". This is what I have so far

public class Passenger {

    private String name;
    private String location;
    private String phoneNumber;

    public Passenger(String name, String location, String phoneNumber) {
        this.name = name;
        this.location = location;
        this.phoneNumber = phoneNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        if (phoneNumber.matches("[a-zA-z]+)")) {
            phoneNumber = "Not Valid";
        } 
        else if (phoneNumber.length() > 10) {
            phoneNumber = "Not Valid";
        }

        else if (phoneNumber.startsWith("1")){
            phoneNumber = "Not Valid";
        }
        else {
        this.phoneNumber = phoneNumber;
        }
    }

    public String toString() {
        return " Name: " + name + "\n Location: " + location + "\n Phone Number: " + phoneNumber;

  public class Test {

    public static void main(String[] args) {

        Passenger one = new Passenger("John John", "China", "1231231234");
        Passenger two = new Passenger("John John", "China", "A");
        Passenger three = new Passenger("John John", "China", "2323232323");
        Passenger four = new Passenger("John John", "China", "123123123123");
        System.out.println(one);
        System.out.println(two);
        System.out.println(three);
        System.out.println(four);
    }

For passenger two, three and four I would expect phone number to show Not Valid, but they are showing the values which were put in.

Any help would be grateful

like image 281
XVShi Avatar asked Aug 01 '19 13:08

XVShi


People also ask

How do I create getters and setters?

How to use: Select a struct type, then press Alt + Enter on Windows/Linux or ⌥ + ⏎ on macOS and choose Generate getter and setter from the list of available actions. Choose which fields should have these methods generated, then press OK to generate them.

Do setters have parameters?

The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.

What will happen if getter and setter are made private?

The private getter/setter methods provide a place for adding extra behavior or error checking code. They can provide a place for logging state changes or access to the fields. They can provide a place for adding your debug code while testing.

What is @getter and @setter in spring boot?

Getters and Setters play an important role in retrieving and updating the value of a variable outside the encapsulating class. A setter updates the value of a variable, while a getter reads the value of a variable.


2 Answers

One could of course, call the setPhoneNumber method within the constructor. But the problem is that you are calling an overridable method within the constructor.

This can lead to problems.

One way is to make a private method containing the validation:

private void validateAndSetPhoneNumber(String phoneNumber) {
    this.phoneNumber = ...
}

And then call it from both the constructor

public Passenger(String name, String location, String phoneNumber) {
    this.name = name;
    this.location = location;
    this.phoneNumber = validateAndSetPhoneNumber(phoneNumber);
}

as from the setter:

public void setPhoneNumber(String phoneNumber) {
    validateAndSetPhoneNumber(phoneNumber);
}

Furthermore, a few notes:

You say you "don't want their phone number to contain any characters". Assuming that you mean "any character other than a digit", your validation is not quite correct. Your current code most certainly throws a PatternSyntaxException because your regex contains an unmatched ). If the regex were [a-zA-z]+, then still the validation were incorrect. For instance, the phone number input abc4def would be considered valid. That is because String.matches tries to match the entire region.

According to your current requirements, the following would suffice:

if (phoneNumber.matches("[02-9]\\d{0,9}")) {
    this.phoneNumber = phoneNumber;
}
else {
    this.phoneNumber = "Not Valid";
}

or just

this.phoneNumber = phoneNumber.matches("[02-9]\\d{0,9}") ? phoneNumber : "Not Valid";

However, I agree with cameron1024's comment.

like image 89
MC Emperor Avatar answered Sep 24 '22 03:09

MC Emperor


Use the method setPhoneNumber in constructor of your class

public Passenger(String name, String location, String phoneNumber) {
    this.name = name;
    this.location = location;
    this.setPhoneNumber(phoneNumber);
}
like image 38
Giuseppe Milicia Avatar answered Sep 24 '22 03:09

Giuseppe Milicia