Scanner sc = new Scanner(System.in);
Boolean valid = true;
do{
valid = true;
//get first name input and valid
System.out.print("Enter your First Name > ");
String firstName = sc.nextLine();
if(firstName.trim().length() > 25){
valid = false;
}
//get last name input and valid
System.out.print("Enter your Last Name > ");
String lastName = sc.nextLine();
if(lastName.trim().length() > 25){
valid = false;
}
//get email input and valid
System.out.print("Enter your Email > ");
String email = sc.nextLine();
if(email.trim().length() > 40){
valid = false;
}
ctrl.addPerson(email, firstName, lastName);
}while(valid == false);
不断提示用户输入无效输入,但仍添加/保存无效数据 (addPerson)。我可以理解为什么保存无效,但我应该如何正确使用 if ?感谢您的帮助!
我已经阅读了大家的建议和建议,以下是编辑后的代码。希望它会更好。
Scanner sc = new Scanner(System.in);
boolean valid = true;
String firstName = null;
String lastName = null;
String email = null;
Date birthday = null;
do{
System.out.print("Enter your First Name > ");
firstName = sc.nextLine();
}while(firstName.trim().length() > 25);
do{
System.out.print("Enter your Last Name > ");
lastName = sc.nextLine();
}while(lastName.trim().length() > 25);
do{
System.out.print("Enter your Email > ");
email = sc.nextLine();
}while(email.trim().length() > 40);
ctrl.addPerson(email, firstName, lastName);