这是我总是得到count = 0并且总是回答“无效”。任何人都可以纠正我

时间:2016-06-12 16:43:21

标签: java

Q值。这里的问题是我总是得到count = 0并且总是回答“无效”。 任何人都可以纠正我。

public class CheckingUsername {
    public static void main(String[] args) {
        isValidUsername("2244awerh");
        // System.out.println("a".matches("[a-zA-A]+") || "w".matches("[0-9]+"));
    }

    // checkin method
    public static void isValidUsername(String username) {
        int count = 0;
        if (username.length() >= 6) {
            for (int i = 0; i < username.length(); i++) {
                // System.out.println(username.charAt(i));
                if ("username.charAt(i)".matches("[a-zA-A]+") || "username.charAt(i)".matches("[0-9]+")) {
                    if ("username.charAt(i)".matches("[0-9]+")) {
                        count = count + 1;
                    }
                }
            } // end of for
            System.out.println(count);
            if (count >= 2) {
                System.out.println("Valid");
            } else
                System.out.println("Invalid");
        } // end of first if
    }// end of method
}// end of class

2 个答案:

答案 0 :(得分:0)

见评论。我希望它能使错误明确:

    public class CheckingUsername {

        public static void main(String[] args) {
            isValidUsername("2244awerh");
            // System.out.println("a".matches("[a-zA-A]+") || "w".matches("[0-9]+"));
        }

        // checkin method
        public static void isValidUsername(String username) {
            int count = 0;
            if (username.length() >= 6) {
                for (int i = 0; i < username.length(); i++) {

                    //"username.charAt(i)" is not a variable. It is a string literal.

                    //make you need a String, not a char to use matches 
                    String charAsString = String.valueOf(username.charAt(i));
                    if ( charAsString.matches("[a-zA-A]+") || charAsString.matches("[0-9]+")) {

                        //if ("username.charAt(i)".matches("[0-9]+")) { //why have the same condition twice ? 
                            count = count + 1;
                        //}
                    }
                } // end of for
               // System.out.println(count);
                if (count >= 2) {
                    System.out.println("Valid");
                } else {
                    System.out.println("Invalid");
                }
            } // end of first if
        }// end of method
    }// end of class

答案 1 :(得分:0)

您只能使用正则表达式进行检查:

public static void isValidUsername(String username) {
    if (username.matches("^[a-zA-Z0-9]{6,}$")) {
            System.out.println("Valid");
    } else {
            System.out.println("Invalid");
    }
}
  • ^表示从头开始
  • $表示结束
  • {6,}表示至少6个字符
  • [a-zA-Z0-9]是允许的字符