Java examples for Language Basics:Console
input String from Console with Scanner
//package com.java2s; import java.util.Scanner; public class Main { public static void main(String[] argv) throws Exception { String question = "java2s.com"; String regex = "java2s.com"; System.out.println(inputString(question, regex)); }//ww w. j a va 2 s . c o m public static String inputString(String question, String regex) { return inputString(question, regex, ""); } public static String inputString(String question, String regex, String help) { String answer = ""; boolean matches = false; System.out.print(messageBox(question)); while (!matches) { answer = new Scanner(System.in).next(); if (answer.matches(regex)) { matches = true; } else { System.out.print(messageBox(help, question)); } } return question; } public static String messageBox(String... messages) { if (messages.length > 0) { int maxLength = messages[0].length(); for (int i = 1; i < messages.length; i++) { if (maxLength < messages[i].length()) { maxLength = messages[i].length(); } } if (maxLength > 0) { StringBuilder sb = new StringBuilder(""); sb.append(String.format("%s%-" + maxLength + "s%s", "+ ", " ", " +\n").replace(" ", "-")); for (String message : messages) { if (message.length() > 0) { sb.append("| ") .append(String.format("%-" + maxLength + "s", message)).append(" |\n"); } } sb.append(String.format("%s%-" + maxLength + "s%s", "+ ", " ", " +").replace(" ", "-")); return sb.toString(); } } return "+-+\n" + "| |\n" + "+-+"; } }