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

想知道如何让循环工作,以便如果长度不够长,我可以让用户重新输入长度?现在当我编译它会说密码不够长,但不会让他们重新输入有效密码。有什么建议么?

4

3 回答 3

2

你很近。

如果您想在之前的尝试无效的情况下重新要求用户输入密码,我会考虑将您的问题readLine()移到 while 循环中。

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.");
    }
}

我还进行了另一项调整:将您的“不够长”消息移动到一个else块中。如果您决定对输入添加更多验证检查,此结构将更有意义。

于 2012-05-13T23:12:55.133 回答
1

将读取名称的部分移动到循环中:

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));
于 2012-05-13T23:12:48.130 回答
0

您需要将 readLine() 添加到循环中,以便name变量获得新密码:

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();
}
于 2012-05-13T23:12:42.740 回答