在Java中检查字符串中的字母大小写(上/下)

时间:2013-04-21 04:17:27

标签: java

我遇到的问题是我无法让我的密码验证程序检查字符串以确保其中一个字符为大写,一个字符为小写,它将检查整个字符串是否为另一个并根据它正在检查的语句打印错误消息。

我查看了这个网站和互联网的答案,我找不到一个。这是作业。

以下是我目前的代码。

import java.util.Scanner;

public class password
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        String password;
        String cont = "y";
        char ch;
        boolean upper = false;
        boolean lower = false;

        System.out.println("Setting up your password is easy. To view requirements enter Help.");
        System.out.print("Enter password or help: ");
        password = stdIn.next();
        ch = password.charAt(0);

        while (cont.equalsIgnoreCase("y"))
        {
            while (password.isEmpty())
            {
                System.out.print("Enter password or help: ");
                password = stdIn.next();       
            }

            if (password.equalsIgnoreCase("help"))
            {
                 System.out.println("Password must meet these requirements." +
                     "\nMust contain 8 characters.\nMust contain 1 lower case letter." +
                     "\nMust contain 1 upper case letter.\nMust contain 1 numeric digit." +
                     "\nMust contain 1 special character !@#$%^&*\nDoes not contain the word AND or NOT.");

                password = "";
            }
            else if (password.length() < 8)
            {
                System.out.println("Invalid password - Must contain 8 charaters.");
                password = "";
            }
            else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                    ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                    {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                    }
                }
            }
            else if (!(Character.isUpperCase(ch)))
            {
                for (int i=0; i<password.length(); i++)
                {       
                    ch = password.charAt(i);

                    if (!Character.isUpperCase(ch))
                    {
                        System.out.println("Invalid password - Must have an Upper Case character.");
                        password = "";
                    }
                }
            }
            else
            {
                System.out.println("Your password is " + password);

                System.out.print("Would you like to change your password? Y/N: ");
                cont = stdIn.next();
                password = "";
            }

            while (!cont.equalsIgnoreCase("y") && !cont.equalsIgnoreCase("n"))
            {
                System.out.print("Invalid Answer. Please enter Y or N: ");
                cont = stdIn.next();
            }
        }
    }
}

9 个答案:

答案 0 :(得分:145)

要确定String是否包含大写字母和小写字母,您可以使用以下内容:

boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());

这允许您检查:

if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");

基本上,这通过检查String是否等于其完全小写或大写等效来实现。如果不是这样,那么必须至少有一个大写或小写的字符。

至于你的其他条件,可以用类似的方式来满足这些条件:

boolean isAtLeast8   = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial   = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT

使用上述适当的错误消息。

答案 1 :(得分:7)

像这样的循环:

else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                   ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                       {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                       }
                     // end if
                } //end for
            }

有一个明显的逻辑缺陷:如果第一个字符不是小写,则输入它,然后测试第二个字符是否不是小写字母。那时你会抛出一个错误。

相反,你应该做这样的事情(不是完整的代码,只是一个例子):

boolean hasLower = false, hasUpper = false, hasNumber = false, hasSpecial = false; // etc - all the rules
for ( ii = 0; ii < password.length(); ii++ ) {
  ch = password.charAt(ii);
  // check each rule in turn, with code like this:
  if Character.isLowerCase(ch) hasLower = true;
  if Character.isUpperCase(ch) hasUpper = true;
  // ... etc for all the tests you want to do
}

if(hasLower && hasUpper && ...) {
  // password is good
} 
else {
  // password is bad
}

当然,除了错误的逻辑之外,您提供的代码段没有代码来测试您的“帮助”选项打印出来的其他条件。正如在其他一个答案中指出的那样,您可以考虑使用正则表达式来帮助您加快查找每个事物的过程。例如,

hasNumber  : use regex pattern "\d+" for "find at least one digit"
hasSpecial : use regex pattern "[!@#$%^&*]+" for "find at least one of these characters"

在代码中:

hasNumber  = password.matches(".*\\d.*");  // "a digit with anything before or after"
hasSpecial = password.matches(".*[!@#$%^&*].*");
hasNoNOT   = !password.matches(".*NOT.*");
hasNoAND   = !password.matches(".*AND.*");

有可能以巧妙的方式组合这些东西 - 但是特别是当你是一个新手正则表达式用户时,最好是有点“缓慢而乏味”,并获得第一次工作的代码(加上你会能够弄清楚你从现在起六个月后做了什么。)

答案 2 :(得分:6)

虽然这段代码可能超出了新手的理解,但可以使用具有正面和负面预测的正则表达式在一行中完成:

boolean ok = 
    password.matches("^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*\\d)(?!.*(AND|NOT)).*[a-z].*");

答案 3 :(得分:3)

这已经很老了,@ SinkingPoint已经在上面给出了一个很好的答案。现在,有了Java 8中可用的功能惯用法,我们可以再给它一个转折。您将有两个lambda:

Function<String, Boolean> hasLowerCase = s -> s.chars().filter(c -> Character.isLowerCase(c)).count() > 0;
Function<String, Boolean> hasUpperCase = s -> s.chars().filter(c -> Character.isUpperCase(c)).count() > 0;

然后在代码中,我们可以像这样检查密码规则:

if (!hasUppercase.apply(password)) System.out.println("Must have an uppercase Character");
if (!hasLowercase.apply(password)) System.out.println("Must have a lowercase Character");

关于其他检查:

Function<String,Boolean> isAtLeast8 = s -> s.length() >= 8; //Checks for at least 8 characters
Function<String,Boolean> hasSpecial   = s -> !s.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
Function<String,Boolean> noConditions = s -> !(s.contains("AND") || s.contains("NOT"));//Check that it doesn't contain AND or NOT

在某些情况下,创建lambda是否在交流意图方面增加了价值是有争议的,但是lambda的好处是它们可以发挥作用。

答案 4 :(得分:2)

我已将@Quirliom上面的答案简化为可以使用的函数:

private static boolean hasLength(CharSequence data) {
    if (String.valueOf(data).length() >= 8) return true;
    else return false;
}

private static boolean hasSymbol(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
    return hasSpecial;
}

private static boolean hasUpperCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasUppercase = !password.equals(password.toLowerCase());
    return hasUppercase;
}

private static boolean hasLowerCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasLowercase = !password.equals(password.toUpperCase());
    return hasLowercase;
}

答案 5 :(得分:0)

快速查看documentation on regular expression sytanx应该会提示告诉它在某个时刻是否包含小写/大写字符。

答案 6 :(得分:0)

这就是我得到的:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter a nickname!");
    while (!scanner.hasNext("[a-zA-Z]{3,8}+")) {
        System.out.println("Nickname should contain only Alphabetic letters! At least 3 and max 8 letters");
        scanner.next();
    }
    String nickname = scanner.next();
    System.out.println("Thank you! Got " + nickname);

在这里阅读正则表达式模式: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

答案 7 :(得分:0)

-n

答案 8 :(得分:0)

function TellFirstCharacterType(inputString){
    var firstCharacter = inputString[0];
    if(isNaN(firstCharacter)){
        if(firstCharacter == firstCharacter.toUpperCase()){
            return "It's a uppercase character";
        }
        else{
            return "It's a lowercase character";
        }
    }
    else{
        return "It's a Number";
    }
}