有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java测试字符串以创建有效密码

我正在创建一个java程序来测试密码的有效性。除了其他一些问题,我完全无法运行它。它编译得很好,但我尝试运行它时出错

当我让它运行时,我的问题是我无法让我的代码正常工作。它需要读取用户输入字符串,并使用代码列出的一些条件测试其有效性。它将一直运行,直到用户输入符合所有三个条件的有效密码。代码在以前运行时,会告诉您错误的条件已被泄露,或者在满足所有要求时会说密码无效

我不太确定如何询问我的代码有什么问题,因为我不知道问题出在哪里

先决条件是我在代码中使用了几种方法

以下是我目前的代码:

import java.util.Scanner; public class Test { public static void main(String[] args){ Scanner input = new Scanner(System.in); // Prompt user to enter a password System.out.print("Enter your password: "); String x = input.nextLine(); UserInput(x); } public static String UserInput(String x) { // Define variables int l = x.length(), count = 0; char n = x.charAt(l); boolean valid = false, condition = false; String c1 = "", s1 = ""; // While loop tests the validity of the password while(valid == false && l <= 0){ if (l < 8){ condition = false; c1 = "A password must have at least eight characters"; continue; } else if (Character.isLetter(n) == false && Character.isDigit(n) == false){ condition = false; c1 = "A password must consist of only letters and digits"; continue; } else condition = true; while (count < 2) { if (Character.isDigit(n) == true) { count++; } } if (count < 2) { condition = false; c1 = "A password must contain at least two digits"; continue; } else { condition = true; } l++; if (condition = true) valid = true; else valid = false; } if (valid == true) s1 = "Valid Passord"; else s1 = "Invalid Password"; String m = s1 + "\n\t" + c1; System.out.println(m); return x; } }

共 (2) 个答案

  1. # 1 楼答案

    设置密码长度-

    int l = x.length(),
    

    然后基于它进行循环

        while(valid == false && l <= 0){ 
    

    你的意思是“循环时……密码长度小于或等于零”吗

    此外,要检查最小数字(请检查我的语法)——

    int ndx = 0;
    while (ndx < l) { 
      if ( Character.isDigit( x.charAt( ndx++ ) ) ) {
         count++;
      }
    }
    

    循环基于你检查的字符,而不是你期望找到的字符

  2. # 2 楼答案

            while (count < 2) {
                    if (Character.isDigit(n) == true) {
                        count++;
                    }
            }
    

    在这个循环中,检查一个字符,如果字符串的最后一个字符不是数字,循环可能是无限的