"If"条件与"do-while loop"?

  • 本文关键字:loop do-while If 条件 java
  • 更新时间 :
  • 英文 :


我有一个方法,它要求用户进行多个输入,并基于这4个值在最后创建一个对象。不允许输入空格或只点击回车键,问题应该循环,直到满足条件为止。

而且,每次输入不被接受时;错误:字段不能为空";应该打印出来。我的do while循环似乎工作正常,只是我不知道在哪里实现我的错误消息,使其在正确的条件下出现?

提前谢谢。

public void registerDog() {
String name = null;
do {
System.out.print("Name?> ");
name = input.nextLine();
} while (name.trim().isEmpty());
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

System.out.print("Breed?> ");
String breed = input.nextLine();
breed = breed.substring(0,1).toUpperCase() + breed.substring(1).toLowerCase();
System.out.print("Weight?> ");
int weight = input.nextInt();
System.out.print("Age?> ");
int age = input.nextInt();
Dog dog = new Dog(name, breed, age, weight);
doggoList.add(dog);
System.out.println("n" + dog.getName() + " has been added to the register.n" + dog.toString());
}

你坚持使用do-while循环有什么原因吗?我会放弃do while,而使用if语句。类似这样的东西:

String name;
while (true) {
System.out.print("Name?> ");
name = input.nextLine();
if (!name.trim().isEmpty()) {
break;
}
System.out.println("%nError: field cannot be empty");
}

您还可以将代码简化为一个方法,并在每次需要用户的值时调用它,而不是为每个值重写相同的代码。该方法可能看起来像这样:

public static String getValueFromUser(String prompt) {
String value;
while (true) {
System.out.print(prompt);
value = input.nextLine();
if (!value.trim().isEmpty()) {
return value;
}
System.out.println("%nError: field cannot be empty");
}
}

最新更新