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

        Encryption pass = new Encryption();

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

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

我将如何使上述陈述成立?我需要这样做,以便如果用户输入的密码不够长或不是有效密码,他们可以一遍又一遍地重新输入。不确定我的 while 循环是否正确,但我必须从我的 isValidLength 方法调用以使其正确。发现的任何错误也会有所帮助。

4

3 回答 3

0

Something similar to this:

while(true){
    //read the password
    ...
    if (isValidLength(password)){
        break;
    }
}
//proceed with encryption
...
于 2012-05-13T20:55:03.080 回答
0

I'd suggest using a do ... while instead of a while loop. In pseudocode:

boolean ok;
do {
    <get user input>
    ok = <check validity of user input>
} while (!ok);

If you must use a while loop, just use the above logic but initialize ok to false:

boolean ok = false;
while (!ok) {
    <get user input>
    ok = <check validity of user input>
}

Also, I think the logic that you currently have in isValidLength is backwards. It will also have to be declared static if it is to be called from main.

于 2012-05-13T20:55:45.717 回答
0

I can see a few things that need attention:

  • Your call to pass.decrypt(name) appears to pass the plaintext entered by the user to a function called decrypt(). Perhaps you wanted to pass the return value of pass.encrypt(name) instead?

  • Your isValidLength() function returns true if the length of the string is less than your minimum. I think you want this the other way around.

For your while loop, I suggest a structure commonly called "loop-and-a-half":

while (true) {
    System.out.println("Please enter a password:");
    String 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));
// ... rest of code

With this construct, the break is in the middle of the loop. The bottom half of the loop is a place to tell the user what they need to do to correct their erroneous input. After the loop ends, you can assume that the user's input has passed the isValidLength() check.

于 2012-05-13T20:56:33.077 回答