将元素添加到数组并再次使用该数组

Adding element to array and using that array again

对于 class 我必须创建一个程序,要求用户输入密码,如果他们输入的密码尚未列出,请将其添加到列表中并允许他们再次输入并且是正确的。我尝试编写一种方法来复制数组并添加新密码,但它不起作用。有人能告诉我我哪里出错了吗?哦,我必须使用数组而不是数组列表:(

public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    String pin;

    do {
        System.out.print("Please enter the password: ");
        pin = console.nextLine();
        checkPassword(pin);
    } while (!checkPassword(pin));



}

public static boolean checkPassword (String pin) {
    String[] passwords = {"9999", "coastal", "1"};

    if (Arrays.stream(passwords).anyMatch(pin::equals)) {
        return true;
    } else {
        int count = 0;
        String[] newWord = new String[passwords.length + 1];
        for(int i=0; i < passwords.length; i++){
             newWord[i]= passwords[i];
             count++;
        }
        newWord[count] = pin;

        passwords = newWord;
        System.out.print("Password was not in array. It has now been added. Try logging in again.");
        return false;
    }
}

根据我对你的问题的理解,你有一个密码列表,你想要做的是要求用户输入密码然后重新插入以验证是否重新插入密码与第一个匹配。

为此,您必须提示用户输入并将收到的密码添加到密码列表中。之后再次提示用户输入相同的密码并检查密码列表中是否存在该密码。如果插入正确,则密码应该存在,因为用户是第一次添加它。

不过,您正在执行的这个实施并不是最好的。尝试使用字典将密码与用户名相关联。您还可以请求 2 个输入并比较它们以验证它们是否相同,然后将密码添加到字典中。

希望对您有所帮助。

你的第一个错误是你使用局部变量作为密码,所以它总是在你调用方法时初始化。

其次,您正在检查密码两次:首先检查,然后循环条件检查。

因此建议您使用一个字段而不是局部变量作为密码,并且只执行一次检查,然后程序将正常运行。

更新代码:

public class Test {
    private static String[] passwords = {"9999", "coastal", "1"};

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        String pin;

        boolean valid = false;
        do {
            System.out.print("Please enter the password: ");
            pin = console.nextLine();
            valid = checkPassword(pin);
        } while (!valid);


    }

    public static boolean checkPassword(String pin) {
        if (Arrays.stream(passwords).anyMatch(pin::equals)) {
            return true;
        } else {
            int count = 0;
            String[] newWord = new String[passwords.length + 1];
            for (int i = 0; i < passwords.length; i++) {
                newWord[i] = passwords[i];
                count++;
            }
            newWord[count] = pin;

            passwords = newWord;
            System.out.print("Password was not in array. It has now been added. Try logging in again.");
            return false;
        }
    }
}

您遇到的问题与变量作用域有关。每当当前方法执行结束时,其变量将超出范围并符合垃圾收集条件。你可以说 passwords 是一个局部变量。

现在,如果您确实在方法中保存了数组的更新版本,它将被丢弃并且对后续调用不可见。

public static boolean checkPassword (String pin) {
    String[] passwords = {"9999", "coastal", "1"};
    ...
} // here, passwords goes out of scope

要修复您的错误,您必须将其全局存储或将其添加为方法参数。

// global
private static String[] passwords = {"9999", "coastal", "1"};

// method parameter
public static boolean checkPassword (String pin, String[] passwords) {
    ...
}