Aug 13, 2014

12. Input


There are several methods of reading from the console. Usually, you will read data from a file rather than from console, but most methods are similar.




System.in is the standard input stream. Its read() method returns the ASCII code, ASCII being a subset of unicode. It is best to type ch=System.in.read(); for example, and then let Eclipse put the try and Exception clause.


  // *** 1. Start (System.in)
  int ch = 0;
  System.out.println("Type something and press Enter");
  boolean bRead = true;
  while (bRead) {
   try {
    ch = System.in.read();
   }
   catch (IOException e) {
    e.printStackTrace();
   }
   if (ch != 13) System.out.print((char)ch + ", ");
   else {
    System.out.println(" End");
    bRead = false;
   }
  }
  // *** 1. End



The Scanner class if often used to read input from the console.


  // *** 2. Start (Scanner)
  Scanner scan = new Scanner(System.in);
  System.out.println("Type something and press Enter");
  String str = scan.next();
  System.out.println(str);
  // *** 2. End



The BufferedReader class may also be used to read input from the console. In programming, there are several ways of doing the same thing. Later, we will see examples of BufferedReader to read files.


  // *** 3. Start (BufferedReader)
  BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
  System.out.println("Type something and press Enter");
  String str1 = null;
  try {
   str1 = br.readLine();
  } catch (IOException e) {
   e.printStackTrace();
  }
  System.out.println(str1);
  // *** 3. End



// Ex12.java
package com.javaAndroid.ex12;

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

public class Ex12 {
 public static void main(String[] args) {
  // *** 1. Start (System.in)
  int ch = 0;
  System.out.println("Type something and press Enter");
  boolean bRead = true;
  while (bRead) {
   try {
    ch = System.in.read();
   }
   catch (IOException e) {
    e.printStackTrace();
   }
   if (ch != 13) System.out.print((char)ch + ", ");
   else {
    System.out.println(" End");
    bRead = false;
   }
  }
  // *** 1. End
  // *** 2. Start (Scanner)
  Scanner scan = new Scanner(System.in);
  System.out.println("Type something and press Enter");
  String str = scan.next();
  System.out.println(str);
  // *** 2. End
  // *** 3. Start (BufferedReader)
  BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
  System.out.println("Type something and press Enter");
  String str1 = null;
  try {
   str1 = br.readLine();
  } catch (IOException e) {
   e.printStackTrace();
  }
  System.out.println(str1);
  // *** 3. End
 }
}



No comments:

Post a Comment