编写程序模拟用户注册:
1、程序开始执行时,提示用户输入“用户名”和“密码”信息。
2、输入信息之后,后台java程序模拟用户注册。
3、注册时用户名要求长度在[6-14]之间,小于或者大于都表示异常。
注意:
完成注册的方法放到一个单独的类中。
异常类自定义即可。
class UserService {
public void register(String username,String password){
//这个方法中完成注册!
}
}
编写main方法,在main方法中接收用户输入的信息,在main方法
中调用UserService的register方法完成注册。
代码实现:
import java.util.Objects;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
UserService userService = new UserService();
Scanner s = new Scanner(System.in);
//注册用户名
System.out.println("请输入要注册的用户名(要求长度在[6-14]之间):");
String userName = s.next();
//注册密码
System.out.println("请输入注册密码:");
String password = s.next();
//注册成功
try{
userService.register(userName,password);
}
catch (UserServiceException e){
e.printStackTrace();
}
}
}
//注册类
class UserService {
private String username;//用户名
private String password;//密码
//构造方法
public UserService() {
}
public UserService(String username, String password) {
this.username = username;
this.password = password;
}
//getter and setter
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void register(String username, String password)throws UserServiceException {
if(username == null || username.length()<6 || username.length()>14){
throw new UserServiceException("用户名不合法,长度必须在[6-14]!");
}
this.username = username;
this.password = password;
System.out.println(this.username+"注册成功!");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserService that = (UserService) o;
return Objects.equals(username, that.username) && Objects.equals(password, that.password);
}
@Override
public String toString() {
return "UserService{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
/**
* 编译时异常
*/
//异常类
class UserServiceException extends Exception{
public UserServiceException(){
}
public UserServiceException(String s){
super(s);
}
}