我无法弄清楚如何使用单个 isValidPassword
方法解决此问题,因此我将其分解为 3 个方法并使其正常工作。有人可以向我解释一下如何使用我编写的代码以及如何压缩它吗?
创建一个密码程序,提示用户输入密码并确定密码是否有效。应该有一个静态方法 isValidPassword 来验证密码(字符串)并返回 true 或 false。用户只能尝试输入有效密码三次。 有效的密码遵循以下三个规则:
- Must have at least eight characters.
- Must contain ONLY letters and digits.
- Must contain at least two digits.
使用程序的对话框。您必须为此程序使用 String 和 Character 类。您不能使用正则表达式。该程序只需要运行一次。
import javax.swing.JOptionPane;
public class Password {
public static void main(String[] args) {
int retryCount = 0;
while (retryCount < 3) {
retryCount++;
String password = JOptionPane.showInputDialog("Please Enter the Password");
if (CheckPassword(password)) {
JOptionPane.showMessageDialog(null, "Congrats! Correct Password!");
break;
}
else {
JOptionPane.showMessageDialog(null, "Sorry, Invalid Password, you tried " + retryCount + " times");
continue;
}
}
}
public static boolean CheckPassword(String password) {
if (password.length() >= 8 & CheckAlphanumeric(password) && Check2digits(password)) {
return true;
}
else {
return false;
}
}
public static boolean CheckAlphanumeric(String string) {
for (int i = 0; i < string.length(); i++) {
char x = string.charAt(i);
if (x < 0x30 || (x >= 0x3a && x <= 0x40) || (x > 0x5a && x <= 0x60) || x > 0x7a) {
return false;
}
}
return true;
}
public static boolean Check2digits(String string) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isDigit(c)) {
count++;
}
if (count > 2) {
return true;
}
}
return false;
}
}
最佳答案
让我们快速回顾一下代码:
- 了解 Java 命名约定。方法名称采用驼峰式命名法;返回 boolean 值的东西应该命名为
isPasswordValid()
例如 - 您在这里所做的实际上是一种很好的方法:人们应该更喜欢许多小方法(带有良好且有意义的名称!)而不是拥有一些大方法(背后的东西称为“单层抽象”原则)里>
- 您可以阅读正则表达式来完成大部分检查;特别是检查“仅 ASCII 字符”是一个不错的选择!因此,即使你的作业说“不要使用它们”;您可能想了解如何使用它们。只为自己的学习进步!但正如卡亚曼指出的那样,Character类有许多用于此类检查的静态辅助方法;因此无需手动实现所有这些。
- 您的代码“逻辑上不一致”。如果某些字符串符合某些密码规则(最小长度、最小位数),则您的代码正在验证。但您的消息暗示此代码正在检查提供的密码是否正确;就像这样:用户输入他的密码,然后代码检查该密码是否已知并且与之前存储的密码匹配。从这个意义上说:确保消息和代码内容一致!
public interface PasswordValidator {
public void checkPassword(String password) throws InvalidPasswordException;
}
然后您创建各种实现,例如
public class MinimumLengthValidator implements PasswordValidator {
@Override
public void checkPassword(String password) throws InvalidPasswordException {
if (password.lenght() < 8) {
throw new InvalidPasswordException("Given password is not long enough; expecting at least 8 characters");
}
}
然后,您创建这些不同 validator 类的实例;并将它们存储在某个数组中。您迭代该数组,并单独调用每个验证;当失败时,您会直接收到一个异常,并为用户提供一条友好的消息。
如前所述:以上内容仅供引用(并且只是打字,因此请注意拼写错误)。
关于java - 我将如何浓缩这些方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41056976/