gpt4 book ai didi

java - 使用堆栈检查密码中相同数量的字母和数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:12:20 24 4
gpt4 key购买 nike

我必须编写一个程序来检查密码,其中密码应该

  • 长度至少应为 8 个字符
  • 只包含字母和数字(特殊字符)
  • 包含相同数量的字母和数字

程序应检查它是否有效并显示适当的消息。此外,只有堆栈类应该用作数据结构。

这是我到目前为止的想法:

public class dsa_1c {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner sc= new Scanner(System.in);

String pass;

System.out.println("Enter a password");
pass= sc.nextLine();

if(checkPass(pass)){
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}


public static boolean checkPass(String password){

Stack<Character> stack= new Stack<Character>();


int count1=0, count2=0;

if(password.length()<8){
return false;
}
else{
for(int i=0; i<password.length();i++){
char c= password.charAt(i);

if (!Character.isLetterOrDigit(c)){
return false;}

if(Character.isLetterOrDigit(c)){

stack.push(c);

}

char top= stack.peek();

if(Character.isLetter(top)){
count1++;
stack.pop();

}

else if(Character.isDigit(top)){
count2++;
stack.pop();

}

if(count1==count2){
return true;
}

if(!stack.isEmpty()){
return false;
}

}

}
return true;

}

}

对于我输入的超过 8 个字符且没有特殊字符的任何密码,程序在运行时会显示“有效密码”。这部分显然是问题所在

if(count1==count2){
return true;}

因为当我改变它的时候

if(count1!=count2)
return false; }

它为任何有效的密码返回无效的密码。

最佳答案

最终导致问题的是 return true。您可以只使用 return count1 == count2;,而不是比较两个计数并返回值。下面是一个例子:

public static boolean checkPass(String password) {

Stack<Character> stack = new Stack<Character>();
int count1 = 0, count2 = 0;
if (password.length() < 8) {
return false;
} else {
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);

if (!Character.isLetterOrDigit(c)) {
return false;
} else {
stack.push(c);
}
}
while(!stack.isEmpty()){
char c = stack.pop();
if(Character.isLetter(c)){
count1++;
}else{
count2++;
}
}
return count1 == count2;
}
}

关于java - 使用堆栈检查密码中相同数量的字母和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com