检查密码 [英] Checking Password Code

查看:180
本文介绍了检查密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题描述:

某些网站对密码规定了某些规则。编写一个检查字符串是否为有效密码的方法。假设密码规则如下:

Some Websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rule is as follows:


  • 密码必须至少包含8个字符。

  • 密码只包含字母和数字。

  • 密码必须至少包含两位数。

编写一个程序,提示用户输入密码,如果遵循规则则显示有效密码,否则显示无效密码。

Write a program that prompts the user to enter a password and displays "valid password" if the rule is followed or "invalid password" otherwise.

这就是我到目前为止:

import java.util.*;  
import java.lang.String;  
import java.lang.Character;  

/**
 * @author CD
 * 12/2/2012
 * This class will check your password to make sure it fits the minimum set     requirements.
 */
public class CheckingPassword {  

    public static void main(String[] args) {  
        Scanner input = new Scanner(System.in);  
        System.out.print("Please enter a Password: ");  
        String password = input.next();  
        if (isValid(password)) {  
            System.out.println("Valid Password");  
        } else {  
            System.out.println("Invalid Password");  
        }  
    }  

    public static boolean isValid(String password) {  
        //return true if and only if password:
        //1. have at least eight characters.
        //2. consists of only letters and digits.
        //3. must contain at least two digits.
        if (password.length() < 8) {   
            return false;  
        } else {      
            char c;  
            int count = 1;   
            for (int i = 0; i < password.length() - 1; i++) {  
                c = password.charAt(i);  
                if (!Character.isLetterOrDigit(c)) {          
                    return false;  
                } else if (Character.isDigit(c)) {  
                    count++;  
                    if (count < 2)   {     
                        return false;  
                    }     
                }  
            }  
        }  
        return true;  
    }  
}

当我运行程序时,它只检查长度密码,我无法弄清楚如何确保它检查字母和数字,并在密码中至少有两位数。

When I run the program it only checks for the length of the password, I cannot figure out how to make sure it is checking for both letters and digits, and to have at least two digits in the password.

推荐答案

你几乎得到了它。但是有一些错误:

You almost got it. There are some errors though:


  • 你没有迭代密码的所有字符( i< password.length() - 1 错误)

  • 你的数字计数为1而不是0

  • 一旦你遇到第一个数字就检查数字位数是否至少为2,而不是在你扫描完所有字符后检查它数

  • you're not iterating over all the chars of the password (i < password.length() - 1 is wrong)
  • you start with a digit count of 1 instead of 0
  • you make the check that the count of digits is at least 2 as soon as you meet the first digit, instead of checking it after you have scanned all the characters

这篇关于检查密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆