010605
J. W. Rider

Basic User Input

System.in.read()

inchar = (char) System.in.read(); // read single character from keyboard


inchar a variable of type char
(char) a typecast that explicitly converts the result from reading the keyboard into a unicode character.
System a class in the java.lang package. (The same class referenced by "System.out.print()".)
in a static (we don't need an object to reference it) field in the class System, the type of in is "InputStream".
read() a method for the class, InputStream.


InputStream.read() is an overloaded method to handle different input tasks.

int read() reads a single character.
int read(bytearray) reads full bytearray
int read(bytearray, offset, length) reads partial bytearray

read() can potentially throw an IOException. Any use of read must be caught in a try statement, or the method with the read must be annotated "throws IOException".

read() doesn't read a whole line at a time. To read a whole line at a time, try a BufferedReader object. For example,


//import java.io.*;

//read line from a buffered reader
public static String readLine(BufferedReader in)
{
   try
   {
     return in.readline();
   }
   catch (IOException e)
   {
   }
   return null;
}


//read line from an input stream
public static String readLine(InputStream is)
{
   try
   {
     BufferedReader in = new BufferedReader(new InputStreamReader(is));
     return readline(in);
   }
   catch (IOException e)
   {
   }
   return null;
}

// read line from System.in
public static String readLine()
{
  return readLine(System.in);
}
1