Receive console input in any of your Java applications - Java Language Basics

Java examples for Language Basics:Console

Description

Receive console input in any of your Java applications

Demo Code

import java.io.BufferedInputStream;
import java.io.IOException;

public class Main {
  public static String readLine() {
    StringBuilder response = new StringBuilder();
    try (BufferedInputStream buff = new BufferedInputStream(System.in)) {

      int in;/*from   www.  j  a  v a2  s .  c  o m*/
      char inChar;
      do {
        in = buff.read();
        inChar = (char) in;
        if ((in != -1) & (in != '\n') & (in != '\r')) {
          response.append(inChar);
        }
      } while ((in != -1) & (inChar != '\n') & (in != '\r'));
      buff.close();
      return response.toString();
    } catch (IOException e) {
      System.out.println("Exception: " + e.getMessage());
      return null;
    }
  }

  public static void main(String[] arguments) {
    System.out.print("\nWhat is your name? ");
    String input = Main.readLine();
    System.out.println("\nHello, " + input);
  }
}

Result


Related Tutorials