2016-06-12 19 views
-6

質問ここで私は常にカウント= 0を取得し、常に "無効"と答えています。 誰でも私を修正してください。ここに私はいつも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 
+3

'' username.charAt(i) 'は( "[a-zA-A] +") 'と一致しますか? 'String.valueOf(username.charAt(i))。matches(...)'と書いてみましたか? – Tunaki

+3

'if(" username.charAt(i) "。(...))は' username'変数の値をまったく使っていません。 '' username.charAt(i) "'は文字列リテラルです... –

+0

String.valueOf(username.charAt(i))。一致(...)もうまくいきません。 –

答えて

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 
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]は許容される文字です
関連する問題