Keyboard input

Download Report

Transcript Keyboard input

Lecture 13: Keyboard Input and
Text Files
Yoni Fridman
7/23/01
Outline


Overview
Input classes



Reading keyboard input



InputStreamReader
BufferedReader
Reading Strings
Converting to other types
Reading from text files
Overview


A stream is a technical term for a whole sequence
of text input. (Think of it as a stream of
characters.)
Whenever Java reads input (from the keyboard,
from a file, etc.), it takes in a stream and stores it
in what’s called a Buffer:
H

e
l
l
o
A Buffer is an object that holds each of the
characters read in from a stream. To be of any use
to us, the Buffer must be converted to a String.
Input Classes

Java has two classes that we’ll need to use to read
input from the keyboard:



InputStreamReader is a class that’s used to read streams from the
keyboard and save them as Buffers.
BufferedReader is a class that’s used to convert a Buffer to a
String.
These classes aren’t automatically available for
our use.


To use them, we need the following command at the very
beginning of our program: import java.io.*;
import is a keyword that tells Java to load certain classes for our
use.
Reading Keyboard Input

Before we can read input from the keyboard, we
must create a new object of the
InputStreamReader class, like this:
InputStreamReader stream = new InputStreamReader(System.in);

Then we must create a new object of the
BufferedReader class, like this:
BufferedReader buffer = new BufferedReader(stream);

Finally, we can read input using the instance
method readLine() of the class BufferedReader:

String input;
input = buffer.readLine();
Converting to Other Types


Input is always read into Strings. Even if we enter
the number 3, Java stores the String “3”.
We can convert to an int like this:


int inputInt;
inputInt = Integer.parseInt(input);
And we can convert to a double like this:


double inputDouble;
inputDouble = Double.valueOf(input).doubleValue();
Reading from Text Files

What if we have text (or any data) that has been
stored in a file?


We can read that as input much like we read keyboard input.
There’s another class that we’ll need to read input
from a text file:

FileReader is a class that’s very similar to InputStreamReader –
it’s used to read streams from a text file.
Reading from Text Files

Instead of creating an InputStreamReader
object, we create a FileReader object, like this:
FileReader file = new FileReader(“data.txt”);
 In this case, data.txt is the name of our text file – this can be any
name we want it to be.

Now, we can use the FileReader object file just
like we used the InputStreamReader object
stream before:

BufferedReader buffer = new BufferedReader(file);
String input = buffer.readLine();
Homework


Read: 13.4, to the bottom of page 568.
HW6 out today, due Friday.

Calculator.