javastringtruthiness

Evaluate truthiness in Java


I am writing an interactive console app in Java. I need to ask the user questions with Boolean responses, however, Scanner.in.nextBoolean() is rather brittle in that it throws exceptions on incorrect input, so wrapping it in a method seems like a good idea. I could just use a try/catch block and insist on the user typing "true" or "false" to answer and catch the typos. But then I thought I could use Scanner.in.next() or Scanner.in.nextLine() and evaluate the returned string for truthiness using something like parseBoolean(String s).

Is there a way to evaluate a string for "truthiness" beyond true/false? That is, "0"/"1" "yes"/"no" would also evaluate to true/false.


Solution

  • What about a custom implementation?

    1. Use a map and define all the values for true and false
    2. Use a list; true if the value is in the list, otherwise false
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    
        // Define true and false values
        Map<String, Boolean> truthiness = new HashMap<>();
    
        truthiness.put("yes", true);
        truthiness.put("1", true);
        truthiness.put("true", true);
        truthiness.put("t", true);
        truthiness.put("ya", true);
        truthiness.put("nein", false);
        //etc
    
        // Define only the true values
        List<String> trueValues = Arrays.asList("yes", "1", "true", "t", "ya");
    
        for(int i = 0; i < 5; ++i) {
            String value = sc.nextLine().toLowerCase();
    
            System.out.println("map: " + truthiness.get(value));
            System.out.println("list: " + trueValues.contains(value));
        }
    }
    

    Output

    yes
    map: true
    list: true
    1
    map: true
    list: true
    t
    map: true
    list: true
    ya
    map: true
    list: true
    nein
    map: false
    list: false