简体   繁体   English

带有“do-while 循环”的“If”条件?

[英]An “If” condition with a “do-while loop”?

I have this method which asks the user for multiple inputs and based on these 4 values an object is created at the end.我有这种方法,它要求用户提供多个输入,并根据这 4 个值在最后创建 object。 Entering whitespaces or just hitting return should not be allowed and the question should loop until the conditions are met.不应允许输入空格或仅按回车键,并且问题应循环直到满足条件。

Also, each time an input is not accepted, the message "Error: field cannot be empty" should be printed out.此外,每次不接受输入时,应打印出消息“错误:字段不能为空”。 My do-while loop seems to be working correctly except that I don't know where to implement my error message to make it appear under the right condition?我的 do-while 循环似乎工作正常,只是我不知道在哪里实现我的错误消息以使其在正确的条件下出现?

Thanks in advance.提前致谢。

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());
}

Is there any reason you're stuck to using a do-while loop?您是否有任何理由坚持使用 do-while 循环? I would just ditch the do-while, and use an if statement instead.我会放弃 do-while,而使用 if 语句。 Something like this:像这样的东西:

String name;

while (true) {
    System.out.print("Name?> ");
    name = input.nextLine();

    if (!name.trim().isEmpty()) {
        break;
    }

    System.out.println("%nError: field cannot be empty");
}

You can also simplify your code by making this into a method, and calling it each time you need a value from the user, rather than rewriting the same code for each value.您还可以通过将其制成方法来简化代码,并在每次需要用户提供值时调用它,而不是为每个值重写相同的代码。 The method might look something like this:该方法可能如下所示:

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM