How to read from standard input in java?

Here is an example to explain how to read from standard input

  • First Example with BufferedReader and InputStreamReader
package com.nourit.javaIO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadstandardInput {

  public static void main(String[] args) {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    try {
      System.out.print("Write something here and press Enter:");
      while ((s = in.readLine()) != null && s.length() != 0) {
        if ("Q".equals(s)) {
                    System.out.println("the program is ended with Q!");
                    System.exit(0);
                }
        System.out.println();
        System.out.println("with Q or empty line terminates the program");
        System.out.println();
      }
      System.out.println("the program is ended with Empty Line!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
  • Secone Example with Scanner
package com.nourit.javaIO;

import java.util.Scanner;

public class ReadstandardInput1 {

  private static Scanner scanner;

  public static void main(String[] args) {
    scanner = new Scanner(System.in);
    while (true) {
      System.out.print("Write something here and press Enter:");;
      String input = scanner.nextLine();

      if ("Q".equals(input)) {
                System.out.println("the program is ended with Q!");
                System.exit(0);//OR break;
            }

      System.out.println("input : " + input);
    }
  }
}

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*