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);
User keeps being prompted for invalid input, but invalid data still added/saved (addPerson).
I can understand why invalid is saved, but how should i use the if correctly? thank you for the help!
I have read everyone’s suggestions and recommendations, below is the editted codes. Hopefully it is better.
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);
You need to put method
addPersonunder condition likeI also suggest you to use primitive types (
booleaninstead ofBoolean), there is no reason to use its object representation here.