beryx / text-io

A library for creating interactive console applications in Java
http://text-io.beryx.org/
Apache License 2.0
342 stars 45 forks source link

withParseErrorMessagesProvider example #15

Closed johnnyboyc closed 6 years ago

johnnyboyc commented 6 years ago

Hi,

Do you happen to have a usage example for InputReader's withParseErrorMessagesProvider interface?

cheers

John

siordache commented 6 years ago

See the code snippet below. I also configured a valueChecker to show the difference between error messages caused by parsing errors and those caused by unacceptable values.

TextIO textIO = TextIoFactory.getTextIO();

int age = textIO.newIntInputReader()
        .withParseErrorMessagesProvider((val, itemName) -> Arrays.asList(
                "Sorry, but " + val + " is not an integer number.",
                "Please enter your age as an integer."
        ))
        .withValueChecker((val, itemName) -> {
            if(val >= 18) return null;
            return Arrays.asList(
                    "You are only " + val + " years old and tried to access an adult site.",
                    "We will inform your parents about it."
            );
        })
        .read("Enter your age");

textIO.getTextTerminal().println("You are " + age + " years old. Get a life!");

textIO.newStringInputReader().withMinLength(0).read("\nPress enter to terminate...");
textIO.dispose();

An example session with the above code produces the following output:

Enter your age: ​five
Sorry, but five is not an integer number.
Please enter your age as an integer.

Enter your age: ​5
Invalid value.
You are only 5 years old and tried to access an adult site.
We will inform your parents about it.

Enter your age: ​55
You are 55 years old. Get a life!

Press enter to terminate... ​
johnnyboyc commented 6 years ago

Perfect. Many thanks!