gpt4 book ai didi

java - 添加/保存的数据无效 (addPerson)

转载 作者:行者123 更新时间:2023-11-30 04:31:33 25 4
gpt4 key购买 nike

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)。我可以理解为什么要保存 invalid,但是我应该如何正确使用 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);

最佳答案

您需要将方法addPerson置于类似的条件下

if(valid) {
ctrl.addPerson(email, firstName, lastName);
}

我还建议您使用原始类型(boolean 而不是 Boolean),没有理由在这里使用它的对象表示。

关于java - 添加/保存的数据无效 (addPerson),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14539442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com