对 Java 很陌生,需要一些帮助来存储乘客详细信息,同时使用 setter/getter 并使用 toString 方法创建输出。
我遇到的问题是,假设我正在存储乘客的电话号码并且不希望他们的电话号码包含任何字符,长度为 10 个数字并以 1 开头,如果出现其中一个,则返回“无效”。
我试图在 setter 中创建 if 语句,但它没有返回“无效”。这是我到目前为止所拥有的
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);
}
对于二号、三号和四号乘客,我希望显示电话号码Not Valid,但它们显示的是输入的值。
任何帮助将不胜感激
森林海
慕桂英546537
慕丝7291255
慕田峪9158850
相关分类