java - 在嵌套 "for"语句时跳出此 "if"循环

标签 java if-statement for-loop break

我正在尝试使用 break; 语句来退出 for 循环。

final int NUM_USERS = 6;                     // Max Number of Users.
UserInfo[] users = new UserInfo[NUM_USERS];  // Array of Users.
int loginCounter = 0;                        // Counts bad login attempts.
int i = 0;                                   // Loop index variable.
String userRole = "";                        // Holds user's role text.

for (loginCounter = 1; loginCounter <= 3; ++loginCounter) {
        // Get User's Credentials.
        System.out.println("Enter Username: ");
        String username = input.next().toLowerCase();
        input.nextLine();                      // Allows User to enter password.
        System.out.println("Enter Password: ");
        String password = input.nextLine();

        String hash = sysLogin.convertToMd5(password);
        for (i = 0; i < users.length; ++i) {
            if (username.equals(users[i].getUsername())) {
                if (hash.equals(users[i].getHash())) {
                    userRole = users[i].getRole();
                    sysLogin.goodLogin();      // Prints Good Login message.
                    break;
                }
            } else {
                sysLogin.badLogin();           // Prints Bad Login message.
            }
        }
    }

发生了什么:

代码将读取usernamepassword,验证这是一个正确的登录,然后再次返回询问用户名和密码。

预期会发生什么:

一旦成功登录,它将 userRole 设置为当前用户的角色,显示 goodLogin 消息,然后退出循环。

最佳答案

break 只会跳出迭代用户列表的内部 for 循环,而不是外部循环。

尝试做这样的事情

boolean login = false;
do {

    // Get User's Credentials.
    System.out.println("Enter Username: ");
    String username = input.next().toLowerCase();
    input.nextLine();                      // Allows User to enter password.
    System.out.println("Enter Password: ");
    String password = input.nextLine();

    // Convert password to MD5 hash.
    String hash = sysLogin.convertToMd5(password);
    for (i = 0; i < users.length; ++i) {
        if (username.equals(users[i].getUsername())) {
            if (hash.equals(users[i].getHash())) {

                login = true;

                userRole = users[i].getRole();
                sysLogin.goodLogin();      // Prints Good Login message.
                break;
            } else {

                sysLogin.badLogin();           // Prints Bad Login message.
            }
        }
    }
} while ( login == false && failCondition == false );

您需要将失败计数加回到循环中,但这应该会给您带来更符合预期的结果。

关于java - 在嵌套 "for"语句时跳出此 "if"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39937875/

相关文章:

java - null 检查语句是否在 java 中不起作用

java - 从上一个循环获取一个值以在当前循环中使用

batch-file - 批处理文件 - 在 for 循环中更改变量值

php - 从 php 中的 for 循环推送关联数组

java - 在 Java 中使用 BiIntPredicate

java - Volley - 从onResponse获取数据

java - DAO 模式中的 TransferObject

Java 风格 : Variable declaration in a switch

c# - 如何查找 Windows 窗体面板中是否存在标签

r - 在管道 %>% 之后插入 if 语句以在自定义函数中返回错误消息