Java examples for Language Basics:Console
input Int from Console using Scanner
//package com.java2s; import java.util.InputMismatchException; import java.util.Scanner; public class Main { public static void main(String[] argv) throws Exception { String question = "java2s.com"; System.out.println(inputInt(question)); }// ww w. j a v a2s. c om public static int inputInt(String question) { int answer = -1; boolean matches = false; System.out.print(messageBox(question)); while (!matches) { try { answer = new Scanner(System.in).nextInt(); matches = true; } catch (InputMismatchException ex) { System.out.println(messageBox( "Csak sz?mokat ?rhatsz be...!", question)); } } return answer; } 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" + "+-+"; } }