Read in String from Console - Java Language Basics

Java examples for Language Basics:Console

Description

Read in String from Console

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(inString());
    }/*from   w ww.  jav a 2  s . co  m*/

    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();
                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();
        } catch (java.io.IOException e) {
            System.out.println("Input error");
        }
    }

    public static void printPrompt(String prompt) {
        System.out.print(prompt + " ");
        System.out.flush();
    }
}

Related Tutorials