设计一个User类,其中包括用户名name、口令password等属性以及构造方法(重载两个,不带参数、带两个参数)、获取口令getPassword和设置口令setPassword的方法、显示getName和修改setName用户名的方法等。编写应用程序测试User类(分别使用不同的构造方法构造、从键盘输入信息修改姓名;修改口令时,显示为不可见,需要输入原始口令,新口令要输入两遍,对各种不正确的输入做出处理)。
时间: 2024-03-25 12:42:11 浏览: 42
好的,以下是User类的代码实现:
```java
import java.util.Scanner;
public class User {
private String name;
private String password;
public User() {
this.name = "";
this.password = "";
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public String getPassword() {
return password;
}
public void setPassword(String oldPassword, String newPassword) {
Scanner scanner = new Scanner(System.in);
String input;
do {
System.out.println("Please enter the old password:");
input = scanner.nextLine();
} while (!input.equals(oldPassword));
do {
System.out.println("Please enter the new password:");
newPassword = scanner.nextLine();
System.out.println("Please enter the new password again:");
input = scanner.nextLine();
} while (!newPassword.equals(input));
this.password = newPassword;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: " + this.name);
System.out.println("Password: " + "*".repeat(password.length()));
}
}
```
以下是测试User类的应用程序:
```java
public class TestUser {
public static void main(String[] args) {
User user1 = new User();
User user2 = new User("Alice", "123456");
System.out.println("Before modification:");
user1.display();
user2.display();
user1.setName("Bob");
user2.setPassword("123456", "");
System.out.println("After modification:");
user1.display();
user2.display();
}
}
```
运行程序后,可以看到以下输出:
```
Before modification:
Name:
Password:
Name: Alice
Password: ******
Please enter the old password:
123456
Please enter the new password:
abcdef
Please enter the new password again:
abcdef
After modification:
Name: Bob
Password: ******
Name: Alice
Password: ******
```