集册 Java实例教程 使用扫描仪从控制台输入Int

使用扫描仪从控制台输入Int

欢马劈雪     最近更新时间:2020-01-02 10:19:05

641
使用扫描仪从控制台输入Int
/**来 自 时   代     Java  公  众  号 - nowjava.com**/

//package com.nowjava;

import java.util.InputMismatchException;

import java.util.Scanner;


public class Main {

    public static void main(String[] argv) throws Exception {

        String question = "nowjava.com";

        System.out.println(inputInt(question));

    }


    public static int inputInt(String question) {

        int answer = -1;

        boolean matches = false;/** 来 自 时代Java公众号**/

        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");

                    }

                }

               
展开阅读全文