我试图找出如何检查a String以验证它是否至少有一个字母和一个数字.我会提前说这是家庭作业,我有点困惑.
有一种方法isLetterOrDigit()方法似乎是正确的方法,但我不如我将如何在我的代码中实现它.这是我在下面使用的代码:
import javax.swing.JOptionPane;
public class Password
{
public static void main(String[] args)
{
String initialPassword;
String secondaryPassword;
int initialLength;
initialPassword = JOptionPane.showInputDialog(null, "Enter Your Passowrd.");
initialLength = initialPassword.length();
JOptionPane.showMessageDialog(null, "initialLength = " + initialLength);
while (initialLength < 6 || initialLength > 10)
{
initialPassword = JOptionPane.showInputDialog(null, "Your password does not meet the length requirements. It must be at least 6 characters long but no longer than 10.");
initialLength = initialPassword.length();
}
//Needs to contain at least one letter and one digit
secondaryPassword = JOptionPane.showInputDialog(null, "Please enter your password again to verify.");
JOptionPane.showMessageDialog(null, "Initial password : " + initialPassword + "\nSecondar Password : " + secondaryPassword);
while (!secondaryPassword.equals(initialPassword))
{
secondaryPassword = JOptionPane.showInputDialog(null, "Your passwords do not match. Please enter you password again.");
}
JOptionPane.showMessageDialog(null, "The program has successfully completed.");
}
}
Run Code Online (Sandbox Code Playgroud)
我想实现在注释部分则会使用的方法isDigit(),isLetter()或isLetterOrDigit()方法,但我只是不知道如何做到这一点.
任何指导将不胜感激.在此先感谢您的帮助.
这应该工作.
public boolean containsBothNumbersAndLetters(String password) {
boolean digitFound = false;
boolean letterFound = false;
for (char ch : password.toCharArray()) {
if (Character.isDigit(ch)) {
digitFound = true;
}
if (Character.isLetter(ch)) {
letterFound = true;
}
if (digitFound && letterFound) {
// as soon as we got both a digit and a letter return true
return true;
}
}
// if not true after passing through the entire string, return false
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39620 次 |
| 最近记录: |