测试字符串以创建有效密码
问题描述:
我正在创建一个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;
}
}
答
您可以设置密码的长度 -
int l = x.length(),
然后循环基于它。
while(valid == false && l <= 0){
是“Loop while ...密码长度小于或等于零”您的意思是?
此外,检查最低位(请检查我的语法) -
int ndx = 0;
while (ndx < l) {
if (Character.isDigit(x.charAt(ndx++))) {
count++;
}
}
基地环路上你检查的人物,而不是你希望找到的东西。
答
while (count < 2) {
if (Character.isDigit(n) == true) {
count++;
}
}
在这个循环中,你检查一个字符,如果字符串不是数字的最后一个字符,循环可能不休。