自定义异常后,使用时出现的问题


public class Demo {
    static String usernames[] ={"张三李四","张三","李四"};
    public static void main(String[] args) throws RegisterException {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入你的名字");
        String username= sc.next();
        check(username);
    }
    public static void check (String username) throws RegisterException {
        for (int i=0;i< usernames.length;i++) {
            if(username.equals(usernames)){
                throw new RegisterException("该用户已经被注册");
            }else {
                System.out.println("成功");
            }
            }

        }
    }

为啥我的代码每次运行的时候都是成功啊,RegisterException是我自定义的异常,请吴彦祖,彭于晏帮忙看看,谢谢了!

usernames是数组啊,怎么会跟你的string一样呢,这样使用下标循环数组对比

img

public class Demo {
 static String usernames[] ={"张三李四","张三","李四"};
            public static void main(String[] args) throws Exception {
                Scanner sc=new Scanner(System.in);
                System.out.println("请输入你的名字");
                String username= sc.next();
                check(username);
            }
            public static void check (String username) throws Exception {
                for (int i=0;i< usernames.length;i++) {
                    if(username.equals(usernames[i])){
                        throw new Exception("该用户已经被注册");
                    } 
                      
                    }
                System.out.println("成功");
                }
}

1.第12行的if语句判断应该使用字符串数组的下标i对应的元素,而不是判断整个字符串数组usernames是否与输入的用户名相等。
2.在循环结束后,需要加上一条语句以告诉用户当前的注册状态(比如说,如果没有抛出异常,则说明该用户名可以使用,否则需要重新输入其他的用户名)

import java.util.Scanner;

public class Demo {
    static String usernames[] = {"张三李四","张三","李四"};

    public static void main(String[] args) throws RegisterException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的名字");
        String username = sc.next();
        check(username);
    }

    public static void check(String username) throws RegisterException {
        for (int i = 0; i < usernames.length; i++) {
            if (username.equals(usernames[i])) { // 修改为判断索引 i 对应的元素
                throw new RegisterException("该用户已经被注册");
            }
        }
        System.out.println("注册成功"); // 添加提示用户注册成功的语句
    }
}

class RegisterException extends Exception {
    public RegisterException(String message) {
        super(message);
    }
}


 for (int i=0;i< usernames.length;i++) {
            if(usernames[i].equals(username)){
                throw new RegisterException("该用户已经被注册");
            }else {
                System.out.println("成功");
            }
            }
 
        }