集册 Java实例教程 从控制台读取字符串

从控制台读取字符串

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

511
从控制台读取字符串

/* 
*来 自
 时   代    Java - nowjava.com
*/

//package com.nowjava;


public class Main {

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

        System.out.println(inString());

    }


    public static String inString(String prompt) {

        inputFlush();

        printPrompt(prompt);

        return inString();

    }


    public static String inString() {

        int aChar;

        String s = "";

        boolean finished = false;


        while (!finished) {

            try {

                aChar = System.in.read();
                /**
                 * 时 代      J a v a   公   众 号 - nowjava.com 提 供 
                **/

                if (aChar < 0 || (char) aChar == '\n')

                    finished = true;

                else if ((char) aChar != '\r')

                    s = s + (char) aChar; // Enter into string

            } catch (java.io.IOException e) {

                System.out.println("Input error");

                finished = true;

            }

        }

        return s;

    }


    public static void inputFlush() {

        int dummy;

        int bAvail;


        try {

            while ((System.in.available()) != 0)

                dummy = System.in.read();

        } 
展开阅读全文