Java Console Prompt prompt(String prompt)

Here you can find the source of prompt(String prompt)

Description

Shorthand for the scanner creation, the posing of the question, and the getting of the response.

License

Open Source License

Parameter

Parameter Description
prompt the string posed to the user.

Return

the user's answer

Declaration

static String prompt(String prompt) 

Method Source Code

//package com.java2s;

import java.util.List;
import java.util.Scanner;

public class Main {
    private static Scanner scan = new Scanner(System.in);

    /** Shorthand for the scanner creation, the posing of the question, and the getting of the response. This version of
     * the prompt method will not return all responses in lower case.
     * @param prompt the string posed to the user.
     * @return the user's answer*/
    static String prompt(String prompt) {
        System.out.print(prompt + "\t");
        return scan.nextLine();
    }//w w w.  ja  va2s . c  om

    /** Sends data and requests that you sanitise it to avoid stupid errors. All responses will be in lower case. This
     * is the only way the data can be effectively sanitised.
     * @param prompt The question posed to the user.
     * @param acceptableAnswers A list of valid responses.
     * @return the user's answer, which is required to be of the list of valid responses */
    static String prompt(String prompt, List<String> acceptableAnswers) {
        String response;
        while (true) {
            response = prompt(prompt).toLowerCase();
            if (acceptableAnswers.contains(response))
                break;
            else
                System.out.println("Please provide an acceptable answer.");
        }
        return response;
    }
}

Related

  1. prompt(String message)
  2. prompt(String message, String defaults)
  3. prompt(String output)
  4. promptEnterKey()
  5. promptHidden(String message)
  6. promptPressEnterToExit()
  7. promptRequired(String message)