简体   繁体   English

嵌套“if”语句时,打破这个“for”循环

[英]Breaking out of this “for” loop while nested “if” statements

I'm trying to use a break; 我正试图break; statement to exit a for loop. 语句退出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.
            }
        }
    }

What is happening: 怎么了:

The code will read in the username and password , verify it is a good login, then return to asking for the username and password, again. 代码将读入usernamepassword ,验证它是一个很好的登录,然后再次返回询问用户名和密码。

What is expected to happen: 预期会发生什么:

Once it hits a successful login, it sets userRole to the current User's role, displayed the goodLogin message, then exits the loop. 一旦成功登录,它userRole设置为当前用户的角色,显示goodLogin消息,然后退出循环。

the break will only break out of the inner for loop where you itterate the user list, and not the outer loop. break只会突破你用于迭代用户列表的内部for循环,而不是外循环。

Try doing some thing like this 尝试做这样的事情

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 );

You would need to add back in the failure count to the loop, but this should give you a more expected result. 您需要将失败计数添加回循环,但这应该会给您一个更期望的结果。

You can attach a label and break to that label ( Java example about labels in branches ): 您可以附加标签并中断到该标签( 关于分支中标签的Java示例 ):

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.
OUTER:
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();

        // 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())) {
                    userRole = users[i].getRole();
                    sysLogin.goodLogin();      // Prints Good Login message.
                    break OUTER;
                }
            else {
                sysLogin.badLogin();           // Prints Bad Login message.
            }
            }
        }
    }

The break; break; statement breaks the inner-most loop; 语句打破了最内层的循环; the outer-most loop will continue executing. 最外面的循环将继续执行。

In the outer-most loop, you would want to have a variable such as bool success = false; 在最外层循环中,您可能希望拥有一个变量,例如bool success = false; . Before breaking in the inner-most loop, assign true , and do a check in the outer-most loop like: 在打破最内层循环之前,指定true ,并在最外面的循环中执行检查,如:

if(success) break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM