java - do while 循环在我不希望它循环时循环

标签 java loops do-while

我有一个 do while 循环,但它不起作用。正如您在我的代码中看到的,如果变量“choice”不等于 p 或 n,则应该循环。即使我选择等于 p 或 n,它也至少循环一次。是我的位置不好还是什么?

    do{
        System.out.println("Enter the name of the contact you would like to update");
        name = sc.nextLine();
        System.out.println("Would you like to update their name(press n) or phone"
                + "number(press p)?");
        choice = sc.nextLine();
        if(choice.equalsIgnoreCase("n")){
            System.out.println("Enter the new name for the contact");
            String name1 = sc.nextLine();
            SQL.updateName(name, name1);
            c = SQL.searchByName(name1);
            if(c != null)
                System.out.printf("Name: %s\t Phonenumber: %s\n", c.getName(), c.getPhone());
            else
                System.out.println(name+" does not exist");
        }
        else if(choice.equalsIgnoreCase("p")){
            System.out.println("Enter the new number for "+name);
            phone = sc.nextLine();
            SQL.updateNumber(name, phone);
            c = SQL.searchByPhone(phone);
            if(c != null)
                System.out.printf("Name: %s\t Phonenumber: %s\n", c.getName(), c.getPhone());
            else
                System.out.println(name+" does not exist");
        }
        }
        while(choice.equalsIgnoreCase("p") == false || choice.equalsIgnoreCase("n") == false);

最佳答案

你的逻辑不正确;任何选择将始终不等于“p”或不等于“n”。仅当它不是 "p" 不是 "n" 时才需要循环。使用&&:

while(choice.equalsIgnoreCase("p") == false && choice.equalsIgnoreCase("n") == false);

关于java - do while 循环在我不希望它循环时循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25923229/

相关文章:

java - 使用 Java 在 flink 中聚合 JSON

java - 我的代码可以编译但不执行。我哪里做错了?在未来的代码中如何避免这种情况?

java - Java中的类加载时间

python - 叠瓦循环和 Python 语法

c - 郭堂迭代不坚持

java - 带有嵌入式 Tomcat 的 RestEasy 不扫描 Controller

sql - 当需要计数器时,避免在 SQL 中使用 while 循环

c - 如何在 while 循环内重置 do while 循环?

c++ - do{}while(0) 有什么用?

javascript - 如何迭代 JSON 中深度嵌套的对象?