Puge-Yiyan Team-Java Simulation Registration Operation Analysis and Code Implementation

Claim:

Simulate the registration operation. If the user name already exists, an exception will be thrown and prompt: the user name has been registered.

analysis:

1) Use an array to save the registered registered names.
2) Scanner to obtain the registered user names entered by the user.
3) Define a method to judge the registered names in the user input. Traverse and store the registered user names to obtain each user’s User name, using the obtained user name and the user name entered by the user to compare
true: the
user name already exists, and a RegisterFailedException is thrown to inform the user that "the user name has been registered";
false:
continue to traverse the comparison.
If the loop is over, it is still not found Duplicate user name, remind the user "registered successfully!"

achieve:

import com.sun.deploy.association.RegisterFailedException;
import java.util.Scanner;

public class Register {
//使用数组保存已经注册过的用户名
static String[] usernames = {"张三", "李四", "王五", "赵六"};

public static void main(String[] args) throws RegisterFailedException {
    //使用Scanner获取用户用户输入注册的用户名
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入你要注册的用户名");
    String username = sc.next();
    checkUsername(username);

}

//定义一个方法,对用户输入中注册名进行判断
public static void checkUsername(String username) throws RegisterFailedException {
    //遍历已经注册过的用户名,获取每一个用户名
    for (String name : usernames) {
        //使用获取到的用户名和输入的用户名进行比较
        if (username.equals(name)) {
            //用户名已经存在,抛出RegisterFailedException异常,告知用户"该用户名已经被注册”;使用throw声明处理
            throw new RegisterFailedException("该用户名已经被注册");
        }

    }
    System.out.println("注册成功!");
}

}

result:

请输入你要注册的用户名
李四
Exception in thread "main" com.sun.deploy.association.RegisterFailedException: 该用户名已经被注册
at demo01.Register.checkUsername(Register.java:40)
at demo01.Register.main(Register.java:29)

Thank you for reading, welcome to correct any deficiencies!

Guess you like

Origin blog.csdn.net/weixin_51749554/article/details/113820339