public class EasyReader
extends java.lang.Object
Appendix to:
Java Methods: Object-Oriented Programming and Data Structures, 3rd AP Edition
(Skylight Publishing 2015, ISBN 978-0-9824775-6-4)
EasyReader provides simple methods for reading keyboard input and text files. All exceptions are handled inside the class and are hidden from the user.
Example: ======= EasyReader kboard = new EasyReader(); System.out.print("Enter input file name: "); String fileName = kboard.readLine(); EasyReader inputFile = new EasyReader(fileName); if (inputFile.bad()) { System.err.println("*** Cannot open " + fileName + " ***"); System.exit(1); } String firstLine = inputFile.readLine(); if (!inputFile.eof()) // or: if (firstLine != null) System.out.println("The first line is : " + firstLine); System.out.print("Enter the maximum number of integers to read: "); int maxCount = kboard.readInt(); int count = 0; while (count < maxCount && !inputFile.eof()) { int k = inputFile.readInt(); if (!inputFile.eof()) { // process or store this number count++; } } inputFile.close(); // optional System.out.println(count + " numbers read");
Constructor and Description |
---|
EasyReader()
Constructs an
EasyReader associated with
System.in . |
EasyReader(java.lang.String fileName)
Constructs an
EasyReader associated with a file for reading. |
Modifier and Type | Method and Description |
---|---|
boolean |
bad()
Checks the status of the file.
|
void |
close()
Closes the file.
|
boolean |
eof()
Checks the EOF status of the file.
|
char |
readChar()
Reads the next character from the file (any character including
a space or a newline character).
|
double |
readDouble()
Reads the next double (without validating its format).
|
int |
readInt()
Reads the next integer (without validating its format).
|
java.lang.String |
readLine()
Reads from the current position in the file up to and including
the next newline character.
|
java.lang.String |
readWord()
Skips whitespace and reads the next word (a contiguous string of
non-whitespace characters), up to but excluding the next space,
newline, etc.
|
public EasyReader()
EasyReader
associated with
System.in
.public EasyReader(java.lang.String fileName)
EasyReader
associated with a file for reading.fileName
- the name or pathname of the file.public void close()
public boolean bad()
public boolean eof()
public char readChar()
null
character
(Unicode 0) if trying to read beyond the EOF.public java.lang.String readLine()
public java.lang.String readWord()
public int readInt()
public double readDouble()
Double.NaN
, if trying to read
beyond the EOF, or if the token read does not represent a valid double.