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