【发布时间】:2017-02-25 19:56:16
【问题描述】:
我必须编写一个程序来检查密码,密码应该是这样的
- 至少应包含 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; }
它返回任何有效密码的无效密码。
【问题讨论】: