Coerces all the forms of Boolean String may return to proper Booleans. - Java java.lang

Java examples for java.lang:boolean

Description

Coerces all the forms of Boolean String may return to proper Booleans.

Demo Code

/*/*  w  ww . j a  v  a 2 s. c o m*/
 * Copyright 2013 Splunk, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"): you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
import org.w3c.dom.Node;
import org.w3c.dom.Text;

public class Main{
    public static void main(String[] argv) throws Exception{
        String s = "java2s.com";
        System.out.println(normalizeBoolean(s));
    }
    /**
     * Coerces all the forms of Boolean String may return to proper Booleans.
     *
     * @param s A String containing the Boolean from String.
     * @return A Java Boolean.
     * @throws MalformedDataException If the string can't be coerced to a Boolean.
     */
    static boolean normalizeBoolean(String s) throws MalformedDataException {
        if (s == null) {
            throw new MalformedDataException(
                    "Cannot interpret null as a boolean.");
        }

        String value = s.trim().toLowerCase();

        if (value.equals("true") || value.equals("t") || value.equals("on")
                || value.equals("yes") || value.equals("y")
                || value.equals("1")) {
            return true;
        } else if (value.equals("false") || value.equals("f")
                || value.equals("off") || value.equals("no")
                || value.equals("n") || value.equals("0")) {
            return false;
        } else {
            throw new MalformedDataException("Cannot interpret string \""
                    + value + "\" as a boolean.");
        }

    }
}

Related Tutorials