JAVA While 循环 - 最后一个 else if 语句不起作用

标签 java loops while-loop

package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
    public static void main(String[] args) {
        System.out.println("What is the password?");
        Scanner new2 = new Scanner(System.in);
        int input = 0;

        while(input <= 5 )
        {
            String password = new2.nextLine();
            if(!password.equals("bluesky123")){
                System.out.println("Incorrect password");
                input++;
            }

            else if("bluesky123".equals(password)) {
                System.out.println("You got it right!");
                break;
            }
            else if(input == 5) {
                System.out.println("maximum number of attempts reached");
                break;
            }
        }    
    }

}

基本上,一旦我完成 5 个循环,它只会显示“密码错误”并中断。不是“最大尝试次数”消息。

最佳答案

请允许我注释一下:

该 if 语句将始终被求值:

        if(!password.equals("bluesky123")){
            System.out.println("Incorrect password");
            input++;
        }

仅当密码为“bluesky123”时才会评估此 if 语句。在这种情况下,它将始终评估为 true

        else if("bluesky123".equals(password)) {
            System.out.println("You got it right!");
            break;
        }

在任何情况下都不会计算此 if 语句。一旦 if-else 找到一个正确的语句,它将跳过该部分中的所有其他语句。

        else if(input == 5) {
            System.out.println("maximum number of attempts reached");
            break;
        }

就您的情况而言,您应该考虑嵌套 if (即一个 if 位于另一个 if 内)。

关于JAVA While 循环 - 最后一个 else if 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666512/

相关文章:

javascript - 内存游戏数组

loops - 比较列表中的所有元素并获取匹配对的可变引用

java - Spring Boot 和执行器服务

Python while 循环不会退出(初学者)

java - 将字节数组转换为十进制

java - 使用准备好的语句从用户输入创建数据库以防止 SQL 注入(inject)

java - 无法找到类 org.codehaus.groovy.grails.commons.DefaultGrailsS​​erviceClass 的具有 Class 参数的构造函数

.each 循环中的 Ruby 性能

C 程序 - 基本计算器

java - 如何将自定义 SSLSocketFactory 注入(inject) Azure Java SDK