John Mac
John Mac

Reputation: 57

Loop to Re Enter

import csci130.*;

public class Driver {
public static void main(String args[]){

    Encryption pass = new Encryption();

    System.out.println("Please enter a password:");
    String name = KeyboardReader.readLine();

    while (true) {
        if (isValidLength(name)) {
            break;
        }
        System.out.println("Your entered password was not long enough.");
    }
    System.out.println("Encrypted Password:  " + pass.encrypt(name));
    System.out.println("Decrypted Password:  " + pass.decrypt(name));
}
}

boolean isValidLength (String password) {
if (password.length()>minLength)    {
    return true;

}   else    {
    return false;
 }
}

Wondering how I could get the loop to work so I can have the user re enter the length if the length is not long enough? Right now when I compile it will say that the password is not long enough, but will not let them re type a valid password. Any suggestions?

Upvotes: 1

Views: 1618

Answers (3)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

You're close.

If you want to re-ask the user to enter a password if the previous attempt was invalid, I would think about moving your question and readLine() into the while loop.

while (true) {
    System.out.println("Please enter a password:");
    String name = KeyboardReader.readLine();
    if (isValidLength(name)) {
        break;
    } else {
        System.out.println("Your entered password was not long enough.");
    }
}

I also made one other adjustment: moving your "not long enough" message into an else block. This structure will make more sense if you decide to add more validation checks on your input.

Upvotes: 2

personak
personak

Reputation: 539

Move the part where the name is read into the loop:

String name;
while (true) {
    System.out.println("Please enter a password:");
    name = KeyboardReader.readLine();
    if (isValidLength(name)) {
        break;
    }
    System.out.println("Your entered password was not long enough.");
}
System.out.println("Encrypted Password:  " + pass.encrypt(name));
System.out.println("Decrypted Password:  " + pass.decrypt(name));

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143886

You need to add the readLine() into the loop so that the name variable gets a new password:

while (true) {
    if (isValidLength(name)) {
        break;
    }
    System.out.println("Your entered password was not long enough.");

    System.out.println("Please enter a password:");
    name = KeyboardReader.readLine();
}

Upvotes: 0

Related Questions