首页 > 解决方案 > 使用 for 循环创建仅包含数字和数字的密码

问题描述

我正在制作一个程序,该程序从用户那里获取一个字符串来创建密码。但是,此密码至少需要 8 个字符或更多,并且只能包含字母(大写和小写)和数字。我已经这样做了,但是,当我在用户输入一个空格(例如:“密码”)或特殊符号(如“%”或“&”)时,该方法仍然返回值 true,使密码当它不应该返回这个时有效,我该如何纠正这个?

import java.util.Scanner;
public class Password
{
    public static void main(String[] args)
    {
        System.out.println("Enter your password");
        Scanner input = new Scanner(System.in);
        String pass = input.nextLine();
        System.out.println("Is the password valid? " + passwordCheck(pass));
    }
    
    public static boolean passwordCheck(String password)
    {   
        boolean pass = false;
        for(int i=0; i < password.length(); i++)
        {
        char c = password.charAt(i);
        if(password.length() >= 8)
        {
            if(c >= 48 && c <= 57)
            {
            pass = true;    
            }
            else if(c>= 97 && c<= 122)
            {
            pass = true; 
            }
            else if(c>=65 && c<=90)
            {
            pass = true;    
            }
            else if(c == 32)
            {
            pass = false;    
            }
        }    
        
        
        }
        return pass;

    }
}

标签: javafor-looppasswords

解决方案


一旦遇到空格或任何其他特殊字符,您就需要跳出循环。

import java.util.Scanner;
public class Password
{
    public static void main(String[] args)
    {
        System.out.println("Enter your password");
        Scanner input = new Scanner(System.in);
        String pass = input.nextLine();
        System.out.println("Is the password valid? " + passwordCheck(pass));
    }
    
    public static boolean passwordCheck(String password)
    {   
        boolean pass = false;
        for(int i=0; i < password.length(); i++)
        {
        char c = password.charAt(i);
        if(password.length() >= 8)
        {
            // also you can directly mention the character instead of looking for its respective ASCII value
            if(c >= '0' && c <= '9')
            {
                pass = true;
            }
            else if(c>= 'a' && c<= 'z')
            {
                pass = true; 
            }
            else if(c>='A' && c<='Z')
            {
                pass = true;
            }
            else // loop will break if it encounters a space or any other 
 special character
            {
                pass = false;    
                break;
            }
        }    
        
        
        }
        return pass;

    }
}

推荐阅读