简体   繁体   中英

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

I'm trying to use a break; statement to exit a for loop.

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.

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.

the break will only break out of the inner for loop where you itterate the user list, and not the outer loop.

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

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; 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; . Before breaking in the inner-most loop, assign true , and do a check in the outer-most loop like:

if(success) break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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