因此,让我们假设我们有这个循环,以字符串的形式从用户那里获得输入。通过该输入,我们想要做的是设置一组验证,以检查是否满足某些条件。如果满足所有这些条件,它将完成相关操作。然而;如果它没有,它会告诉他们错误并重新启动该过程。
我的问题是验证字符串中字母的存在(或不存在)。我有这个程序,对于其中一个验证,我需要检查整个字符串。如果字符串中没有至少一个不是字母的字符,我想暂停操作并解释需要非字母字符。
问题在于我不确定如何在if循环中的表达式中复制它。这是我到目前为止所拥有的。
public static changePassword() // Method that runs through the process of changing the password.
{
// Retrieving the current and new password from the user input.
System.out.println("Welcome to the change password screen.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your current password: ");
String currentPassword = keyboard.nextLine();
System.out.print("Please enter the new password: ");
String newPassword1 = keyboard.nextLine();
System.out.print("Please enter the new password again: ");
String newPassword2 = keyboard.nextLine();
// Validating the new password entry.
if (newPassword1.equals(newPassword2)) // Checking to see if the new password was entered exactly the same twice.
{
if (newPassword1.length() >= 6) // Checking to see if the new password has 6 or more characters.
{
if (**some expression**) // Checking to see if the password has at least one non-letter character.
{
currentPassword = newPassword1 // If all conditions are met, it sets the current password to the password entered by the user.
}
else // If there isn't a non-letter character, it informs the user and restarts the process.
{
System.out.println("The new password must have a non-letter character.");
changePassword();
}
}
else // If there is less than 6 characters, it informs the user and restarts the process.
{
System.out.println("The new password can not be less than 6 characters.");
changePassword();
}
}
else // If the new passwords don't match, it informs the user and restarts the process.
{
System.outprintln("The passwords must match.");
changePassword();
}
}
答案 0 :(得分:0)
假设“letter”是指A-Z中的英文字符,a-z,只是遍历字符串,如果遇到int值超出字母范围的字符,则返回true。
public static boolean containsNonLetter(String s){
for(int i = 0; i < s.length(); i++){
int ind = (int)s.charAt(i);
if(ind < 65 || (ind > 90 && ind < 97) || ind > 122)
return true;
}
return false;
}
答案 1 :(得分:0)
我假设通过信件你的意思是字母。如果使用正则表达式模式,您可以拥有非常干净的代码,并且您可以根据需要更新模式。要了解详情,请查看Java Pattern。这是代码。
private static final Pattern APLHA = Pattern.compile("\\p{Alpha}");
public static boolean hasLetter(String input) {
return APLHA.matcher(input).find();
}