使用扫描仪从控制台输入字符串
//package com.nowjava; import java.util.Scanner;/** 时 代 Java 公 众 号 - nowjava.com 提供 **/ public class Main { public static void main(String[] argv) throws Exception { String question = "nowjava.com"; String regex = "nowjava.com"; System.out.println(inputString(question, regex)); } 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;/*时 代 Java - nowjava.com 提 供*/ 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"); }