Read in Char from console - Java Language Basics

Java examples for Language Basics:Console

Description

Read in Char from console

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String prompt = "java2s.com";
        System.out.println(inChar(prompt));
    }//from ww  w  .  j a  v  a 2 s .c o  m

    public static char inChar(String prompt) {
        int aChar = 0;

        inputFlush();
        printPrompt(prompt);

        try {
            aChar = System.in.read();
        } catch (java.io.IOException e) {
            System.out.println("Input error");
        }
        inputFlush();
        return (char) aChar;
    }

    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