2016-11-28 67 views
0

我試圖編寫一個程序,提示用戶輸入密碼,然後根據密碼是否爲「有效」,在命令提示符處輸出密碼或告訴用戶再次輸入密碼。用戶有3次嘗試,直到程序終止。在用戶密碼無效的情況下執行while循環

我的循環,應該運行,直到passString變量有效(由isPasswordValid方法確定)或用戶有三次嘗試。

問題是我的while循環從不執行,即使我將passString初始化爲「無效」密碼。 isPasswordValid在程序第一次運行時應該返回false,因此執行循環。

目前我的程序打印出「你的密碼是:」,它沒有打印密碼,因爲循環從不執行,因此從不提示用戶輸入密碼。

import javax.swing.*; 
import java.util.*; 
public class Password { 

    public static void main(String[] args) { 

     JPanel panel = new JPanel(); 
     JLabel label = new JLabel("Enter a password:"); 
     JPasswordField pass = new JPasswordField(10); 

     //place the label and the password field on the JPanel container 
     panel.add(label); 
     panel.add(pass); 

     String[] options = new String[]{"OK", "Cancel"}; 

     int tries = 0; 

     String passString = ""; 

     while (!isValidPassword(passString) && tries < 3) { 
      //I've tried isValidPassword(passString) == false 
      //and the loop still did not execute 

      int option = JOptionPane.showOptionDialog(null, panel, "The title", 
      JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE, 
      null, options, options[1]); 

      char[] password = pass.getPassword(); 

      StringBuilder glue = new StringBuilder(); 

      for (int x = 0; x < password.length; x++) { 

      glue.append(password[x]); 
      passString = glue.toString(); 

      } 
      tries++; 
     } 


     System.out.print("Your password is: " + passString); 

    } 

    public static boolean isValidPassword(String word) { 
     int intCounter = 0; 
     int letCounter = 0; 

     for (int x = 0; x < word.length(); x++) { 

      if (Character.isDigit(x)){ 

       intCounter++; 
      } 


      if(Character.isLetter(x)) { 

       letCounter++;   

      } 

      if(!Character.isLetterOrDigit(x)) { 

       return false; 

      }  

     } 


     if (intCounter >= 2 && word.length() <= 8) { 

      return true; 

     } 

    return true; 


    } 
} 

回答

0

它看起來對我來說,你的isValidPassword功能不佔空字符串傳遞到它,所以它完全跳過你的主要「爲」塊,然後在最末端默認返回true功能。如果字符串爲空,您需要在一開始就返回false。

+0

我已添加: if(word.isEmpty()){ return false; } 我的方法。該程序現在成功提示用戶輸入密碼。現在的問題是,即使我輸入的密碼符合「有效」密碼所需的標準,程序也會不斷詢問用戶,直到用完嘗試並退出循環。 –

+0

我不確定什麼構成有效的密碼。從閱讀你的功能,我會說這是: – MattCash

+0

必須是1到8個字符的長度,必須包括至少2位數字,不能包含特殊字符。它是否正確? @Jason_Silva – MattCash