如何创建一个Java程序来检查您的密码是否正确?

shr*_*dan 3 java passwords

我希望程序执行2件事:

  1. 检查字符串(密码输入)是否同时包含字母和数字。
  2. 检查密码是否至少包含8个字符。

这是我的代码:

import java.util.*;
class howstrong
{
  public static void main(String ar[])
  {
    String password;
    int i;
    int c=0;
    Scanner in = new Scanner(System.in);
    System.out.println("ENTER PASSWORD");
    password = in.next();
    if (password.length() <= 8)
    {
      for (i = 0; i <= password.length(); i++)
      {
        char x = password.charAt(i);
        if (Character.isLetter(x))
        {
          if (Character.isDigit(x))
          c = 1;
        }
      }
      if (c == 1)
        System.out.println("STRONG");
      else 
        System.out.println("NOT STRONG");
    }
    else
      System.out.println("HAVE AT LEAST 8 CHARACTERS");
  }
}
Run Code Online (Sandbox Code Playgroud)

Arn*_*aud 5

您有几个问题:

i <= password.length() 应该 i < password.length()

if (password.length() <= 8) 应该 if (password.length() >= 8)

您正在检查字符是否同时是字母和数字。

最后,我建议使用两个标志,一个用于检测是否存在字母,另一个用于检测是否存在数字。

全部放在一起:

import java.util.Scanner;

class howstrong {
    public static void main(final String ar[]) {
        String password;
        Scanner in = new Scanner(System.in);
        System.out.println("ENTER PASSWORD");
        password = in.next();

        boolean hasLetter = false;
        boolean hasDigit = false;

        if (password.length() >= 8) {
            for (int i = 0; i < password.length(); i++) {
                char x = password.charAt(i);
                if (Character.isLetter(x)) {

                    hasLetter = true;
                }

                else if (Character.isDigit(x)) {

                    hasDigit = true;
                }

                // no need to check further, break the loop
                if(hasLetter && hasDigit){

                    break;
                }

            }
            if (hasLetter && hasDigit) {
                System.out.println("STRONG");
            } else {
                System.out.println("NOT STRONG");
            }
        } else {
            System.out.println("HAVE AT LEAST 8 CHARACTERS");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)