import java.awt.Component;
import javax.swing.JOptionPane;
public class DoSomething {
public static void main(String[] args) {
String password = JOptionPane.showInputDialog(null,
"Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
Component frame = null;
int counter = 0;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
if (password.matches("a-zA-Z")) {
counter++;
character= true;
}
}
if(Character.isLetterOrDigit(c)) {
counter++;
symbol = false;
}
if(Character.isDigit(c)) {
counter++;
if (counter >=2) {
number = true;
}
if (password.length()>=8) {
length = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog("Your Password " +password +" is valid")
}
}
}
编辑 - 它仍然讨厌长度(即使是8个或更多)
为什么不使用正则表达式?
public static boolean isValid(String password) {
return password.matches("([a-zA-Z]{8,})([0-9]{2,})");
}
此表达式(如果我没记错的话)检查是否有8个或更多字符(小写和大写)和如果密码中有两个以上的数字。$, @,[space]之类的符号会触发表达式为false。编辑:此正则表达式仅允许使用8个(或更多)分组字符和2个(或更多)号码的密码。数字不能分开(1mypassword3),因为这会将密码标记为无效。需要进一步调查。
有关正则表达式请参见Java API:
Java 7模式类
Java 8模式类
还请查看String.Matches(String Regex)
评论反应
此代码应该更适合您:
int letterCount = 0;
int numberCount = 0;
/*
* Loop through the password and count all the letters and characters
*/
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.toString(c).matches("[a-zA-Z]")) {
letterCount++;
}
if (Character.toString(c).matches("[0-9]")) {
numberCount++;
}
}
if (letterCount > 8) {
// password has 8 or more characters
}
if (numberCount > 2) {
// password has more than 2 numbers
}
然后,如果您也确实想检查长度,则可以添加此代码(在循环外)
if (password.length() >= 10) {
/* Since we need 2 numbers and 8 characters, the password
* can never be valid if it's smaller than 10 characters
*/
else {
/*
* Invalid password
*/
}
假设您的有效密码条件为:
- 至少8个字母
- 至少2个数字
- 没有符号
-
至少10个字符长
String password = JOptionPane.showInputDialog(null, "Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
int letterCounter = 0;
int numCounter = 0;
Component frame = null;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
letterCounter++;
}
else if(Character.isDigit(c)) {
numCounter++;
}
else {
symbol = true;
}
}
//Checking booleans
if (password.length()>=10) {
length = true;
}
if (letterCounter>=8) {
character = true;
}
if (numCounter>=2) {
number = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog(frame, "Your Password " + password + " is valid");
System.out.println("Success");
}
else {
System.out.println("Invalid");
}