2014-09-01 88 views
0

因此,让我们想象一下,我们有这个循环以字符串的形式从用户获得输入。有了这个输入,我们想要做的就是设置一组验证来检查是否符合某些标准。如果满足所有这些条件,它将完成有问题的操作。然而;如果没有,它会告诉他们错误并重新启动过程。在循环中搜索一个非字母字符的字符串

我的问题是关于验证字符串中字母的存在(或不存在)。我有这个程序,对于其中一个验证,我需要检查整个字符串。如果字符串没有至少一个不是字母的字符,我想停止该操作并解释需要使用非字母字符。

问题是,我不知道如何在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

你可以使用'regex'试试这个[link](http://stackoverflow.com/questions/9587907/how-to-check-if-string-has-at-least-one-letter -number-和特殊字符的) – 2014-09-01 02:18:43

回答

0

由“信”假设你的意思是在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; 
} 
0

我假设你的信是你的意思是字母。如果你使用正则表达式模式,你可以有一个非常干净的代码,你可以根据需要更新模式。要了解更多,请检查Java Pattern。这是代码。

private static final Pattern APLHA = Pattern.compile("\\p{Alpha}"); 

public static boolean hasLetter(String input) { 

    return APLHA.matcher(input).find(); 
}