首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 控制台實現用戶登錄驗證邏輯(含重試次數限制)

     編輯:Java 相關知識

代碼實現

import java.util.Scanner;

public class LoginDemo {
    private static final String CORRECT_USER = "jim";
    private static final int CORRECT_PASS = 123456;
    private static final int MAX_ATTEMPTS = 3;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int attempts = 0;

        while (attempts < MAX_ATTEMPTS) {
            System.out.print("請輸入用戶名: ");
            String user = scanner.nextLine().trim();
            
            System.out.print("請輸入密碼: ");
            int pass;
            try {
                pass = Integer.parseInt(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.out.println("密碼必須為數字!");
                continue; // 不計入嘗試次數
            }

            attempts++;
            
            if (CORRECT_USER.equals(user) && CORRECT_PASS == pass) {
                System.out.println("歡迎登入 MyShopping 系統");
                break;
            } else {
                int remaining = MAX_ATTEMPTS - attempts;
                if (remaining > 0) {
                    System.out.printf("輸入錯誤,還有 %d 次機會%n", remaining);
                } else {
                    System.out.println("對不起,您已連續 3 次輸入錯誤,帳號暫時鎖定。");
                }
            }
        }
        scanner.close();
    }
}

關鍵點解析

要點說明
輸入處理Scanner.nextLine() 讀取整行,避免 next() 僅讀取首個 token 導致換行符殘留
密碼類型示例用 int,實際應用絕不可用明文整數存儲密碼,需哈希(BCrypt/SCrypt/PBKDF2)
字符串比較"jim".equals(user) 防空指針,常量在前
循環控制while (attempts < MAX_ATTEMPTS) 比 for 更清晰表達重試語義
異常處理捕獲 NumberFormatException 避免程序崩潰,非數字輸入不計次數
資源關閉scanner.close() 釋放系統資源(System.in 關閉後不可重開)

安全性缺陷與改進方向

  1. 明文密碼:生產環境必須存儲鹽值哈希,驗證時 BCrypt.checkpw(input, storedHash)。
  2. 硬編碼憑證:應從配置文件/數據庫/密碼管理器讀取。
  3. 無鎖定機制:僅控制台提示,實際應記錄失敗次數、IP、時間,達閾值鎖定賬戶/IP(Redis 計數器 + TTL)。
  4. 無加密傳輸:控制台輸入可見,Web 應用必須 HTTPS + 前端加密(RSA/OAEP)。
  5. 無會話管理:登入成功後應生成 JWT/Session ID,後續請求攜帶 Token 驗證。

擴展:圖形界面版本

// Swing 簡易登錄框
JFrame frame = new JFrame("登錄");
JTextField userField = new JTextField(15);
JPasswordField passField = new JPasswordField(15);
JButton loginBtn = new JButton("登錄");
loginBtn.addActionListener(e -> {
    String user = userField.getText();
    char[] pass = passField.getPassword();
    // 驗證邏輯...
});
// 佈局添加組件...
frame.pack(); frame.setVisible(true);

總結

本示例演示了 Java 控制台程序中基本的輸入驗證、循環重試、異常處理流程。雖然邏輯簡單,但涵蓋了輸入處理、狀態控制、資源管理等基礎編程要素。**切記:此代碼僅供教學演示,絕不可直接用於生產環境認證系統。**

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved