java 要求:注册时,要判断用户名是否被占用,是:则禁止注册。 编写一个账号类(存储正确的用户名和密码) 登录时,要判断用户名、密码和验证码(随机四位字母和数字组成),同时正确才能登录成功,
时间: 2024-06-11 17:09:37 浏览: 85
否则提示登录失败。
账号类代码:
```
public class Account {
private String username;
private String password;
public Account(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
```
注册时判断用户名是否被占用的代码:
```
List<Account> accounts = new ArrayList<Account>();
// 假设已经有一些账号存在于 accounts 中
String newUsername = "newUser";
boolean usernameExists = false;
for (Account account : accounts) {
if (account.getUsername().equals(newUsername)) {
usernameExists = true;
break;
}
}
if (usernameExists) {
System.out.println("该用户名已被占用,请重新输入!");
} else {
// 进行注册操作
}
```
登录时判断用户名、密码和验证码的代码:
```
String inputUsername = "username";
String inputPassword = "password";
String inputCaptcha = "ABCD"; // 假设用户输入的验证码为 ABCD
Account accountToLogin = null;
for (Account account : accounts) {
if (account.getUsername().equals(inputUsername) && account.getPassword().equals(inputPassword)) {
accountToLogin = account;
break;
}
}
if (accountToLogin == null) {
System.out.println("用户名或密码错误,请重新输入!");
} else if (!inputCaptcha.equals(captcha)) {
System.out.println("验证码错误,请重新输入!");
} else {
// 登录成功,进行后续操作
}
```