XVS*_*Shi 12 java getter-setter
Java相当新,希望在使用setter / getters并使用toString方法创建输出时存储乘客详细信息方面有所帮助。
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);
}
Run Code Online (Sandbox Code Playgroud)
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
小智 2
在类的构造函数中使用 setPhoneNumber 方法
public Passenger(String name, String location, String phoneNumber) {
this.name = name;
this.location = location;
this.setPhoneNumber(phoneNumber);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |