gpt4 book ai didi

JAVA密码检查程序-检查密码是否有2位以上数字+仅字母和数字

转载 作者:太空宇宙 更新时间:2023-11-04 13:15:38 25 4
gpt4 key购买 nike

好吧,我正在制作一个密码检查程序,并且有一些规则。密码必须为 8 个或更多字符密码必须包含 2 位或更多数字密码只能是字母和数字这是我到目前为止所拥有的如何检查 2 位数字以及仅字母和数字?谢谢

import java.util.Scanner;

public class checkPassword {

public static boolean passwordLength(String password) {
boolean correct = true;
int digit = 0;

if (password.length() < 8) {
correct = false;
}
return correct;
}


public static void main(String[] args) {
// Nikki Kulyk


//Declare the variables
String password;

Scanner input = new Scanner(System.in);

//Welcome the user
System.out.println("Welcome to the password checker!");

//Ask the user for input
System.out.println("Here are some rules for the password because we like to be complicated:\n");
System.out.println("A password must contain at least eight characters.\n" +
"A password consists of only letters and digits.\n" +
"A password must contain at least two digits.\n");
System.out.println("Enter the password: ");
password = input.nextLine();

boolean correct = passwordLength(password);


if (correct) {
System.out.println("Your password is valid.");
}
else {
System.out.println("Your password is invalid.");
}

}
}

最佳答案

这里有一个解决方案。虽然效率不高,但对初学者应该有帮助。它将问题分解为步骤。对密码的每一项要求都会一次一步地进行测试。如果在任何时候违反了其中一项要求,该方法将返回 false;一旦我们确定密码无效,就没有必要进行更多检查。

该方法首先检查长度(如上所述)。然后它使用 for 循环来计算字符串中的位数。接下来,它使用正则表达式来确保密码中仅包含字母数字字符。在测试字符串是否为字母数字时,请注意逻辑否定 (!) 运算符。如果字符串只包含字母和数字,则返回 false。

其中包含注释以说明和阐明逻辑。祝你好运。

public static boolean passwordLength(String password) {
/* Declare a boolean variable to hold the result of the method */
boolean correct = true;

/* Declare an int variable to hold the count of each digit */
int digit = 0;

if (password.length() < 8) {
/* The password is less than 8 characters, return false */
return false;
}

/* Declare a char variable to hold each element of the String */
char element;

/* Check if the password has 2 or more digits */
for(int index = 0; index < password.length(); index++ ){

/* Check each char in the String */
element = password.charAt( index );

/* Check if it is a digit or not */
if( Character.isDigit(element) ){
/* It is a digit, so increment digit */
digit++;
} // End if block

} // End for loop

/* Now check for the count of digits in the password */
if( digit < 2 ){
/* There are fewer than 2 digits in the password, return false */
return false;
}

/* Use a regular expression (regex) to check for only letters and numbers */
/* The regex will check for upper and lower case letters and digits */
if( !password.matches("[a-zA-Z0-9]+") ){
/* A non-alphanumeric character was found, return false */
return false;
}

/* All checks at this point have passed, the password is valid */
return correct;

}

关于JAVA密码检查程序-检查密码是否有2位以上数字+仅字母和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com