Java Scanner Usage confirm(String message)

Here you can find the source of confirm(String message)

Description

confirm

License

Open Source License

Parameter

Parameter Description
message to display

Return

true if user enters y

Declaration

public static boolean confirm(String message) 

Method Source Code

//package com.java2s;
/*/*w  w  w  .jav a2 s  . com*/
 * Scaffold Hunter
 * Copyright (C) 2006-2008 PG504
 * Copyright (C) 2010-2011 PG552
 * Copyright (C) 2012-2014 LS11
 * See the file README.txt in the root directory of the Scaffold Hunter
 * source tree for details.
 *
 * Scaffold Hunter is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scaffold Hunter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static final String NEW_LINE = "\n";

    /**
     * @param message
     *            to display
     * @return true if user enters y
     */
    public static boolean confirm(String message) {
        out(NEW_LINE, message + " (Y/N): ");

        String response = scanner.nextLine();
        return response != null && response.trim().toUpperCase().equals("Y");
    }

    /**
     * @param message
     *            to display
     * @param defaultValue
     *            defaultValue
     * @return true if user enters y, false if user enter n and all other cases
     *         it returns defaultValue
     */
    public static boolean confirm(String message, boolean defaultValue) {
        out(NEW_LINE, message + (defaultValue ? " [Y] " : " [N] ") + "(Y/N): ");
        String response = scanner.nextLine();
        return response == null ? defaultValue
                : response.trim().toUpperCase().equals("Y") ? true
                        : response.trim().equalsIgnoreCase("N") ? false : defaultValue;
    }

    /**
     * Display all message to console
     * 
     * @param messages
     */
    public static void out(String... messages) {
        for (String message : messages) {
            System.out.print(message);
        }
    }
}

Related

  1. calcCompileWarnings(String compilerResult)
  2. cleanUpEmptyLinesAndIndent(String input)
  3. close()
  4. common(Scanner in)
  5. computeSumTable(Scanner in, short n)
  6. confirm(String message)
  7. confirmAction(String warning)
  8. countFileLines(Scanner fin)
  9. createKeyboardScanner()