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;
}
}
想知道如何让循环工作,如果长度不够长,我可以让用户重新输入长度吗?现在当我编译它时会说密码不够长,但不会让他们重新输入有效的密码。有什么建议吗?
答案 0 :(得分: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
块中。如果您决定在输入上添加更多验证检查,则此结构将更有意义。
答案 1 :(得分: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));
答案 2 :(得分: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();
}