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 關閉後不可重開) |
BCrypt.checkpw(input, storedHash)。// 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 控制台程序中基本的輸入驗證、循環重試、異常處理流程。雖然邏輯簡單,但涵蓋了輸入處理、狀態控制、資源管理等基礎編程要素。**切記:此代碼僅供教學演示,絕不可直接用於生產環境認證系統。**