Java Scanner Usage isYes(String str)

Here you can find the source of isYes(String str)

Description

is Yes

License

Open Source License

Declaration

public static boolean isYes(String str) 

Method Source Code

//package com.java2s;
/*************************************************************************
 *
 *  The Contents of this file are made available subject to the terms of
 *  the Sun Industry Standards Source License Version 1.2
 *
 *  Sun Microsystems Inc., March, 2001//w w w. j a  v a  2  s .  c  o  m
 *
 *
 *  Sun Industry Standards Source License Version 1.2
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.2 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *   The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *   Copyright: 2001 by Sun Microsystems, Inc.
 *
 *   All Rights Reserved.
 *
 ************************************************************************/

import java.util.InputMismatchException;

import java.util.Scanner;

public class Main {
    public static final String PATTERN_YES_NO = "y(es)?|no?";

    public static boolean isYes(String str) {
        return getYesNoAsInt(str) == 1 ? true : false;
    }

    public static int getYesNoAsInt(String str) {
        str = str.toLowerCase();
        if (!isValueValid(str, PATTERN_YES_NO)) {
            throw new IllegalArgumentException(str + " is not a yes_no type");
        }
        if (str.startsWith("y")) {
            return 1;
        } else if (str.startsWith("n")) {
            return 0;
        } else {
            throw new IllegalArgumentException("YesNoAsInt coversion error for input: " + str);
        }
    }

    private static boolean isValueValid(String value, String pattern) {
        Scanner s = new Scanner(value);
        try {
            s.next("^(" + pattern + ")$");
            return true;
        } catch (InputMismatchException ex) {
            return false;
        }
    }
}

Related

  1. input(String message)
  2. input(String prompt)
  3. isInteger(String s)
  4. isNumeric(String str)
  5. isValueValid(String value, String pattern)
  6. iterate(final String node)
  7. joinSqlStatements(Collection scripts)
  8. leerOpcion(String opciones, String msgUsr, String msgErr)
  9. leerTexto(String msgUsr)