Java用户认证循环异常:首次输错后正确用户名仍提示错误
用户认证代码问题修复
问题根源
- 首次输入错误用户名后,进入
else块的do-while循环,但循环内仅调用in.nextLine()读取输入,未将新输入的值赋值给username变量。因此循环中username始终是第一次输入的错误值,即便第二次输入正确,判断条件仍会判定用户名错误,无法进入密码输入环节。 - 密码验证成功后,
System.exit(0)放在提示语句之前,导致加载提示永远无法被执行。
修复后的代码
import java.util.Scanner; class User_Authentication { public static void main(String args[]) { Scanner in = new Scanner(System.in); String username; // 循环获取用户名,直到输入正确 do { System.out.println("Enter your Username"); username = in.nextLine(); if (!username.equals("xyz")) { System.out.println("Incorrect username"); System.out.println("Please try again"); } } while (!username.equals("xyz")); // 用户名正确,进入密码验证流程 System.out.println("Enter the Password"); String password = in.nextLine(); if (password.equals("xyz1234")) { System.out.println("Welcome"); System.out.println("Please wait while the system is loading...."); System.exit(0); } else { System.out.println("Your system has been locked for security reasons."); System.out.println("Please contact an administrator to reset the password"); System.out.println("Any attempt to break in the computer will result in self destruction."); System.exit(0); } } }
修复说明
- 重构用户名输入逻辑:将用户名输入放入
do-while循环内,每次输入后更新username变量,确保判断条件基于最新输入值。 - 调整退出语句位置:将
System.exit(0)移至提示输出之后,保证用户能看到加载提示内容。 - 简化代码结构:移除冗余分支判断,让整体逻辑更清晰易懂。
内容的提问来源于stack exchange,提问作者ShelbyCodersPrivate.ltd
相关产品推荐
相关产品推荐

