为什么我的Java while循环输入正确值后仍重复执行?
密码验证程序错误提示问题解决
你的问题出在代码逻辑顺序上:当前代码在获取用户输入后,不管输入是否正确都会执行System.out.println("Incorrect password");,而while循环的条件判断是在下一次循环开始前才会触发。当你输入正确密码时,当前循环的打印语句已经执行完毕,之后才会检查循环条件,发现不满足后退出,所以错误提示和成功提示会同时出现。
修正方案一:增加输入正确性判断
在打印错误提示前,先判断输入是否和密码不匹配,只有不匹配时才打印提示:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String password = "java123"; String userInput = ""; while (!userInput.equals(password)) { System.out.println("Enter password:"); userInput = input.nextLine(); // 仅当输入错误时打印提示 if (!userInput.equals(password)) { System.out.println("Incorrect password"); } } System.out.println("Access granted"); } }
修正方案二:使用do-while循环(更推荐)
do-while循环会先执行一次循环体再判断条件,避免初始空字符串的冗余判断,逻辑更简洁:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String password = "java123"; String userInput; do { System.out.println("Enter password:"); userInput = input.nextLine(); // 输入错误时才打印提示 if (!userInput.equals(password)) { System.out.println("Incorrect password"); } } while (!userInput.equals(password)); System.out.println("Access granted"); } }
这两种方案都能实现预期效果:输入正确密码后立即终止循环,不再打印错误提示。
内容的提问来源于stack exchange,提问作者RobertoLeiva15
相关产品推荐
相关产品推荐

