2017-01-20 138 views
-2

當我輸入的密碼沒有什麼要求時,它不會讓我重試密碼來獲得禮儀密碼。我該如何解決。我不知道這是一個循環的事情還是什麼。這裏是我的代碼:該java代碼重試該怎麼辦

import java.util.Scanner; 

public class Password { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    int min =8; 
    int max=16; 
    int digit=0; 
    int special=0; 
    int upCount=0; 
    int loCount=0; 
    String password; 
    Scanner scan = new Scanner(System.in); 
    System.out.println(" Enter Your Password:"); 
     password = scan.nextLine(); 
    if(password.length()>=min&&password.length()<=max){ 
     for(int i =0;i<password.length();i++){ 
      char c = password.charAt(i); 
      if(Character.isUpperCase(c)){ 
       upCount++; 
      } 
      if(Character.isLowerCase(c)){ 
       loCount++; 
      } 
      if(Character.isDigit(c)){ 
       digit++; 
      } 
      if(c>=33&&c<=46||c==64){ 
       special++; 
      } 
     } 
     if(special>=1&&loCount>=1&&upCount>=1&&digit>=1){ 
      System.out.println(" Password accepted!"); 
     } 

    } 

    if(password.length()<min){ 

     for(int i =0;i<password.length();i++){ 
      char c = password.charAt(i); 
      if(Character.isLowerCase(c)){ 
       loCount++; 
      } 
      } 

     if(loCount>0){ 
      System.out.println(" Password must be atleat "+min+" characters"); 
    } 
    } 
    else if(password.length()<min&&upCount>1){ 
     for(int i =0;i<password.length();i++){ 
     char c =password.charAt(i); 
     if(Character.isLowerCase(c)){ 
      loCount++; 
     } 
     if(Character.isUpperCase(c)){ 
      upCount++; 
     } 
     } 
     if(loCount>0&&upCount>0){ 
     System.out.println(" Password must be atleast "+min+" chracters:"); 
     System.out.println(" You need atleast one digit:"); 
     System.out.println(" You need atleast one special chracter:"); 
    } 
    } 
    if(password.length()>max||password.length()>=max&&upCount>1&&loCount>1&&digit>1){ 
     System.out.println(" Password is too long.Limit is "+max+" chracters:"); 
       System.out.println(" You need atleast one special chracter:"); 

     } 
     if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit>0&&special==0){ 
     System.out.println(" You need atleast a special chracter"); 
    } 
     if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit==0&&special==0){ 
     System.out.println(" You need atleast one digit:"); 
     System.out.println(" You need atleast one special chracter:"); 
    } 
    } 
} 
+3

A [做,而(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html)將是一個良好的開端 – MadProgrammer

+0

好了,所以我還需要什麼來做那個工作?它會在我的if語句中出現嗎? @MadProgrammer – ally

+0

如果你想不止一次地做某件事,你會想要某種循環(最有可能是'do something ...}(somethingIsTrue);' –

回答

0
password = scan.nextLine(); 

您已經添加了此行唯一的一次,因此它不會再接受密碼。 每當您的密碼驗證失敗時,您都必須再次調用此密碼。一些其他提示:

您現有的所有if()應更新一個boolean字段和一個消息字段,例如isPasswordOkpasswordMessage。然後加入

System.out.println(passwordMessage); 

if(!isPasswordOk){ 
password = scan.nextLine(); 
}