简体   繁体   中英

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. 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?

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? I would just ditch the do-while, and use an if statement instead. 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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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