SlideShare a Scribd company logo
Description
1) Create a Lab2 folder for this project
2) Use the main driver program (called Writers.java) that I
provide below to write files of differing types. You can copy
and paste this code, but make sure the spaces variable copies
correctly. The copy and paste operation eliminates the spaces
between the quotes on some systems.
3) In the writers program, fill in the code for the three classes
(Random, Binary, and Text). In each class, you will need a
constructor, a write method, and a close method. The
constructor opens the file, the write method writes a record, and
the close method closes the file.
4) Other than what I just described, don't change the program
in any way. The program asks for a file type (random, binary, or
text) and the name of the file to create. In a loop it inputs a
person's name (string), a person's age (int), and a person's
annual salary (double). It writes to a file of the appropriate
type. The loop terminates when the user indicates that inputting
is complete. The program then asks if another file should be
created. If the answer is yes, the whole process starts again.
This and all of the java driver programs should be saved in your
lab2 folder but not in the cs258 sub-folder.
5) Note: The method signatures for accessing all of the three
types of files (binary, random, and text) are on the class web-
site. Go to power point slides and click on week two. This will
help if you didn't take accurate notes in class.
6) Write a main program to read binary files (BinReader.java).
This program only needs to be able to read and display records
from a Binary file that was created by the writers program.
7) Write a main program to read random files
(RandReader.java). This program only needs to be able to read
and display records from a Binary file that was created by the
writers program. Make sure that this program reads and displays
records in reverse order. DO NOT USE AN ARRAY!!!
8) In your Lab2 folder, create a subfolder within lab2 named
cs258. Download Keyboard.java from the class web-site to that
folder. Add a new first line of Keyboard.java with the
statement, package cs258;. This line will make Keyboard.java
part of the cs258 package. The driver program shown below has
an import ‘cs258.*;’ statement to access the java files in this
package.
9) Modify Keyboard.java. We want to extend this class so it
can be extended to allow access to multiple files. The changes
follow:
a. Remove all static references. This is necessary so that there
will be an input stream variable (in) in each object.
b. Change the private modifier of the in and current_token
variables to protected. Change the private modifier to protected
in all of the signature lines of the overloaded getNextToken
methods.
c. Create a constructor that instantiates the input stream for
keyboard input. Remove the instantiation from the original
declaration line for the in variable. The constructor doesn't need
any parameters.
10)Create a class TextRead in the file TextRead.java; store this
file in the cs258 folder. This class should also be part of the
cs258 package so be sure to include the package statement. This
class should extend the Keyboard class, so all of
Keyboard.java’s methods are available. It should contain a
constructor that instantiates a sequential text file stream. It
needs also to include an end of file and a close method. Note
that since it extends the Keyboard class, all of Keyboard's
methods are available. The class API follows:
public class TextRead extends Keyboard
{ public TextRead(String filename) {}
public boolean close() {}
public boolean endOfFile() {}
}
Your job is to complete these three methods.
11)I’ve included the source for the program to read text files
(TextReader.java) and display its contents. It uses two files, so
make sure that your modified TextRead program works with it.
Be careful if you cut and paste this program. The string variable
spaces doesn't cut and paste correctly. You will have to correct
it appropriately. Do not make any other changes to this
program.
12)Answer the synthesis questions in an rtf or doc file
(answers.rtf or answers.doc). Type your name and the lab
number on this file and include the questions with the answers.
13)Zip your Eclipse project along with the synthesis answers
and email to [email protected]
// This program reads the SeqText.dat and seqText2.dat files.
// These files were created by TextWriter.
// They are in sequential text format.
// They contain records of name, age, and salary.
import java.io.*;
import java.text.*;
import cs258.*;
public class TextReader
{ public static final int NAME_SIZE=30;
public static void main(String args[])
{ String name;
int age;
double salary;
if (!new File("seqtext.dat").exists() ||
!new File("seqtext2.dat").exists())
{ System.out.println("Files don't exist");
System.exit(1);
}
TextRead file1 = new TextRead("seqtext.dat");
TextRead file2 = new TextRead("seqtext2.dat");
NumberFormat money =
NumberFormat.getCurrencyInstance();
DecimalFormat fmt = new DecimalFormat("##0.##");
String spaces = " ";
System.out.println("Text file readern");
do
{ if (!file1.endOfFile())
{ name = file1.readString();
age = file1.readInt();
salary = file1.readDouble();
System.out.print(name);
if (name.length() < NAME_SIZE)
System.out.print
( spaces.substring(0, NAME_SIZE-name.length())
);
System.out.println
( " " + fmt.format(age) + " " +
money.format(salary) );
}
if (!file2.endOfFile())
{ name = file2.readString();
age = file2.readInt();
salary = file2.readDouble();
System.out.print(name);
if (name.length() < NAME_SIZE)
System.out.print
( spaces.substring(0, NAME_SIZE-name.length())
);
System.out.println
( " " + fmt.format(age) + " " +
money.format(salary) );
}
} while (!file1.endOfFile()||!file2.endOfFile());
file1.close();
file2.close();
System.out.println("nTextReader complete; data printed");
}
}
// This program writes different types of files.
// Random, Binary, and Text.
// Created 3/29/2004 for the lab 2 cs258 project.
import java.io.*;
import java.security.*;
public class Writers
{ private final static int RECORDSIZE = 128;
private final static int NAME_SIZE = 30;
private final static String spaces = " ";
// Keyboard input stream.
private final static BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[])
{
// File related variables variables.
Writer out = null;
String fileType = null, fileName = null;
// Data variables.
String name;
int age, recordNumber = 0;
double salary;
String doMore;
boolean quit, moreFiles;
System.out.println("File writer program");
do
{ try
{ do
{ System.out.print("Enter file type (text, binary,
random): ");
fileType = in.readLine().toLowerCase();
} while ( !("text".startsWith(fileType) ||
"binary".startsWith(fileType) ||
"random".startsWith(fileType))
);
System.out.print("Enter the file name: ");
fileName = in.readLine().toLowerCase();
switch (fileType.charAt(0))
{ case 't': out = new Text(fileName);
break;
case 'b': out = new Binary(fileName);
break;
case 'r': recordNumber = 0;
out = new Random( fileName,
RECORDSIZE);
break;
default: throw new InvalidParameterException();
}
do
{
System.out.print("Enter Name: ");
name = in.readLine() + spaces;
name = name.substring(0,NAME_SIZE);
age = getAge();
salary = getSalary();
out.write(name, age, salary, recordNumber);
recordNumber++;
System.out.println("n Type 'quit' to exit: ");
doMore = in.readLine().toLowerCase();
quit = (doMore.length()>0 &&
"quit".startsWith(doMore));
} while (!quit);
}
catch (InvalidParameterException e)
{ System.out.println("Unknown case");
System.exit(1);
}
catch (IOException e)
{ System.out.println("I/O Error");
}
catch (Exception e)
{ System.out.println("Illegal Entry");
}
finally { try { out.close(); } catch(Exception e) {} }
System.out.println("Another file? (y/n) ");
try
{ doMore = in.readLine().toLowerCase();
moreFiles = (doMore.length()>0 &&
"yes".startsWith(doMore));
}
catch (Exception e) {moreFiles = false;}
} while (moreFiles);
System.out.println("File write complete; data is in
"+fileName+"n");
} // End void main()
// Method to input an age.
private static int getAge()
{ int age = -1;
String inputString = null;
do
{ try
{ System.out.print("Enter Age: ");
inputString = in.readLine();
age = Integer.parseInt(inputString);
if (age<0 || age>100) throw new Exception();
return age;
}
catch (Exception e) {System.out.println("Illegal age, try
again");}
} while (true);
}
// Method to input a salary.
private static double getSalary()
{ double salary = -1;
String inputString = null;
do
{ try
{ System.out.print("Enter Salary: ");
inputString = in.readLine();
salary = Double.parseDouble(inputString);
if (salary<0 || salary>1000000) throw new Exception();
return salary;
}
catch (Exception e) {System.out.println("Illegal salary,
try again");}
} while (true);
}
}
abstract class Writer
{ public abstract void write(String name, int age, double salary,
int record)
throws IOException;
public abstract void close();
}
class Random extends Writer
{ RandomAccessFile out;
int recordSize;
public Random(String fileName, int recordSize)
throws FileNotFoundException
{ }
public void write(String name, int age, double salary, int
record)
throws IOException
{ }
public void close()
{ }
}
class Binary extends Writer
{ DataOutputStream out = null;
public Binary(String fileName) throws IOException
{ }
public void write(String name, int age, double salary, int
record)
throws IOException
{ }
public void close()
{ }
}
class Text extends Writer
{ PrintWriter out = null;
public Text(String fileName) throws IOException
{ }
public void write(String name, int age, double salary, int
record)
throws IOException
{ }
public void close()
{ }
}
//***************************************************
*****************
// Keyboard.java
//
// Facilitates keyboard input by abstracting details about input
// parsing, conversions, and exception handling.
//***************************************************
*****************
import java.io.*;
import java.util.*;
public class Keyboard
{
//************* Error Handling Section
**************************
private static boolean printErrors = true;
private static int errorCount = 0;
//-----------------------------------------------------------------
// Returns the current error count.
//-----------------------------------------------------------------
public static int getErrorCount() {return errorCount;}
//-----------------------------------------------------------------
// Resets the current error count to zero.
//-----------------------------------------------------------------
public static void resetErrorCount (int count) {errorCount =
0;}
//-----------------------------------------------------------------
// Returns a boolean indicating whether input errors are
// currently printed to standard output.
//-----------------------------------------------------------------
public static boolean getPrintErrors() {return printErrors;}
//-----------------------------------------------------------------
// Sets a boolean indicating whether input errors are to be
// printed to standard output.
//-----------------------------------------------------------------
public static void setPrintErrors (boolean flag) {printErrors
= flag;}
//-----------------------------------------------------------------
// Increments the error count and prints the error message if
// appropriate.
//-----------------------------------------------------------------
private static void error (String str)
{ errorCount++;
if (printErrors) System.out.println (str);
}
//************* Tokenized Input Stream Section
******************
private static String current_token = null;
private static StringTokenizer reader;
private static BufferedReader in
= new BufferedReader (new
InputStreamReader(System.in));
//-----------------------------------------------------------------
// Gets the next input token assuming it may be on
subsequent
// input lines.
//-----------------------------------------------------------------
private static String getNextToken() {return getNextToken
(true);}
//-----------------------------------------------------------------
// Gets the next input token, which may already have been
read.
//-----------------------------------------------------------------
private static String getNextToken (boolean skip)
{ String token;
if (current_token == null) token = getNextInputToken
(skip);
else
{ token = current_token;
current_token = null;
}
return token;
}
//-----------------------------------------------------------------
// Gets the next token from the input, which may come from
the
// current input line or a subsequent one. The parameter
// determines if subsequent lines are used.
//-----------------------------------------------------------------
private static String getNextInputToken (boolean skip)
{ final String delimiters = " tnrf";
String token = null;
try
{ if (reader == null)
reader = new StringTokenizer(in.readLine(), delimiters,
true);
while (token == null || ((delimiters.indexOf (token) >= 0)
&& skip))
{ while (!reader.hasMoreTokens())
reader = new StringTokenizer(in.readLine(),
delimiters,true);
token = reader.nextToken();
}
}
catch (Exception exception) {token = null;}
return token;
}
//-----------------------------------------------------------------
// Returns true if there are no more tokens to read on the
// current input line.
//-----------------------------------------------------------------
public static boolean endOfLine() {return
!reader.hasMoreTokens();}
//************* Reading Section
*********************************
//-----------------------------------------------------------------
// Returns a string read from standard input.
//-----------------------------------------------------------------
public static String readString()
{ String str;
try
{ str = getNextToken(false);
while (! endOfLine())
{ str = str + getNextToken(false);
}
}
catch (Exception exception)
{ error ("Error reading String data, null value returned.");
str = null;
}
return str;
}
//-----------------------------------------------------------------
// Returns a space-delimited substring (a word) read from
// standard input.
//-----------------------------------------------------------------
public static String readWord()
{ String token;
try
{ token = getNextToken();
}
catch (Exception exception)
{ error ("Error reading String data, null value returned.");
token = null;
}
return token;
}
//-----------------------------------------------------------------
// Returns a boolean read from standard input.
//-----------------------------------------------------------------
public static boolean readBoolean()
{ String token = getNextToken();
boolean bool;
try
{ if (token.toLowerCase().equals("true")) bool = true;
else if (token.toLowerCase().equals("false")) bool = false;
else
{ error ("Error reading boolean data, false value
returned.");
bool = false;
}
}
catch (Exception exception)
{ error ("Error reading boolean data, false value
returned.");
bool = false;
}
return bool;
}
//-----------------------------------------------------------------
// Returns a character read from standard input.
//-----------------------------------------------------------------
public static char readChar()
{ String token = getNextToken(false);
char value;
try
{ if (token.length() > 1)
{ current_token = token.substring (1, token.length());
} else current_token = null;
value = token.charAt (0);
}
catch (Exception exception)
{ error ("Error reading char data, MIN_VALUE value
returned.");
value = Character.MIN_VALUE;
}
return value;
}
//-----------------------------------------------------------------
// Returns an integer read from standard input.
//-----------------------------------------------------------------
public static int readInt()
{ String token = getNextToken();
int value;
try
{ value = Integer.parseInt (token);
}
catch (Exception exception)
{ error ("Error reading int data, MIN_VALUE value
returned.");
value = Integer.MIN_VALUE;
}
return value;
}
//-----------------------------------------------------------------
// Returns a long integer read from standard input.
//-----------------------------------------------------------------
public static long readLong()
{ String token = getNextToken();
long value;
try
{ value = Long.parseLong (token);
}
catch (Exception exception)
{ error ("Error reading long data, MIN_VALUE value
returned.");
value = Long.MIN_VALUE;
}
return value;
}
//-----------------------------------------------------------------
// Returns a float read from standard input.
//-----------------------------------------------------------------
public static float readFloat()
{ String token = getNextToken();
float value;
try
{ value = (new Float(token)).floatValue();
}
catch (Exception exception)
{ error ("Error reading float data, NaN value returned.");
value = Float.NaN;
}
return value;
}
//-----------------------------------------------------------------
// Returns a double read from standard input.
//-----------------------------------------------------------------
public static double readDouble()
{ String token = getNextToken();
double value;
try
{ value = (new Double(token)).doubleValue();
}
catch (Exception exception)
{ error ("Error reading double data, NaN value returned.");
value = Double.NaN;
}
return value;
}
}

More Related Content

Similar to Description 1) Create a Lab2 folder for this project2.docx

7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Lab 1 Essay
Lab 1 EssayLab 1 Essay
Lab 1 Essay
Melissa Moore
 
Write a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdfWrite a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdf
atulkapoor33
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
wilcockiris
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
SAurabh PRajapati
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
Gagan Agrawal
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentalssirmanohar
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
Saifur Rahman
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
Papu Kumar
 

Similar to Description 1) Create a Lab2 folder for this project2.docx (20)

7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Lab 1 Essay
Lab 1 EssayLab 1 Essay
Lab 1 Essay
 
Write a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdfWrite a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdf
 
15. text files
15. text files15. text files
15. text files
 
Files nts
Files ntsFiles nts
Files nts
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
 
working with files
working with filesworking with files
working with files
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 

More from theodorelove43763

Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docxExam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
theodorelove43763
 
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docxEvolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
theodorelove43763
 
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docxexam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
theodorelove43763
 
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docxEvolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
theodorelove43763
 
Evidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docxEvidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docx
theodorelove43763
 
Evidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docxEvidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docx
theodorelove43763
 
Evidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docxEvidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docx
theodorelove43763
 
Evidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docxEvidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docx
theodorelove43763
 
Evidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docxEvidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docx
theodorelove43763
 
Everyone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docxEveryone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docx
theodorelove43763
 
Even though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docxEven though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docx
theodorelove43763
 
Even though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docxEven though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docx
theodorelove43763
 
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docxEvaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
theodorelove43763
 
Evaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docxEvaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docx
theodorelove43763
 
Evaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docxEvaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docx
theodorelove43763
 
Evaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docxEvaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docx
theodorelove43763
 
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback  Addressi.docxEvaluating 19-Channel Z-score Neurofeedback  Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
theodorelove43763
 
Evaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docxEvaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docx
theodorelove43763
 
Evaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docxEvaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docx
theodorelove43763
 
Evaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docxEvaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docx
theodorelove43763
 

More from theodorelove43763 (20)

Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docxExam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
 
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docxEvolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
 
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docxexam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
 
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docxEvolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
 
Evidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docxEvidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docx
 
Evidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docxEvidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docx
 
Evidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docxEvidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docx
 
Evidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docxEvidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docx
 
Evidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docxEvidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docx
 
Everyone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docxEveryone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docx
 
Even though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docxEven though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docx
 
Even though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docxEven though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docx
 
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docxEvaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
 
Evaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docxEvaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docx
 
Evaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docxEvaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docx
 
Evaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docxEvaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docx
 
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback  Addressi.docxEvaluating 19-Channel Z-score Neurofeedback  Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
 
Evaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docxEvaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docx
 
Evaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docxEvaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docx
 
Evaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docxEvaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docx
 

Recently uploaded

Landownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptxLandownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptx
JezreelCabil2
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Ashish Kohli
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 

Recently uploaded (20)

Landownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptxLandownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 

Description 1) Create a Lab2 folder for this project2.docx

  • 1. Description 1) Create a Lab2 folder for this project 2) Use the main driver program (called Writers.java) that I provide below to write files of differing types. You can copy and paste this code, but make sure the spaces variable copies correctly. The copy and paste operation eliminates the spaces between the quotes on some systems. 3) In the writers program, fill in the code for the three classes (Random, Binary, and Text). In each class, you will need a constructor, a write method, and a close method. The constructor opens the file, the write method writes a record, and the close method closes the file. 4) Other than what I just described, don't change the program in any way. The program asks for a file type (random, binary, or text) and the name of the file to create. In a loop it inputs a person's name (string), a person's age (int), and a person's annual salary (double). It writes to a file of the appropriate type. The loop terminates when the user indicates that inputting is complete. The program then asks if another file should be created. If the answer is yes, the whole process starts again. This and all of the java driver programs should be saved in your lab2 folder but not in the cs258 sub-folder. 5) Note: The method signatures for accessing all of the three types of files (binary, random, and text) are on the class web- site. Go to power point slides and click on week two. This will help if you didn't take accurate notes in class. 6) Write a main program to read binary files (BinReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program. 7) Write a main program to read random files (RandReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program. Make sure that this program reads and displays
  • 2. records in reverse order. DO NOT USE AN ARRAY!!! 8) In your Lab2 folder, create a subfolder within lab2 named cs258. Download Keyboard.java from the class web-site to that folder. Add a new first line of Keyboard.java with the statement, package cs258;. This line will make Keyboard.java part of the cs258 package. The driver program shown below has an import ‘cs258.*;’ statement to access the java files in this package. 9) Modify Keyboard.java. We want to extend this class so it can be extended to allow access to multiple files. The changes follow: a. Remove all static references. This is necessary so that there will be an input stream variable (in) in each object. b. Change the private modifier of the in and current_token variables to protected. Change the private modifier to protected in all of the signature lines of the overloaded getNextToken methods. c. Create a constructor that instantiates the input stream for keyboard input. Remove the instantiation from the original declaration line for the in variable. The constructor doesn't need any parameters. 10)Create a class TextRead in the file TextRead.java; store this file in the cs258 folder. This class should also be part of the cs258 package so be sure to include the package statement. This class should extend the Keyboard class, so all of Keyboard.java’s methods are available. It should contain a constructor that instantiates a sequential text file stream. It needs also to include an end of file and a close method. Note that since it extends the Keyboard class, all of Keyboard's methods are available. The class API follows: public class TextRead extends Keyboard { public TextRead(String filename) {} public boolean close() {} public boolean endOfFile() {} }
  • 3. Your job is to complete these three methods. 11)I’ve included the source for the program to read text files (TextReader.java) and display its contents. It uses two files, so make sure that your modified TextRead program works with it. Be careful if you cut and paste this program. The string variable spaces doesn't cut and paste correctly. You will have to correct it appropriately. Do not make any other changes to this program. 12)Answer the synthesis questions in an rtf or doc file (answers.rtf or answers.doc). Type your name and the lab number on this file and include the questions with the answers. 13)Zip your Eclipse project along with the synthesis answers and email to [email protected] // This program reads the SeqText.dat and seqText2.dat files. // These files were created by TextWriter. // They are in sequential text format. // They contain records of name, age, and salary. import java.io.*; import java.text.*; import cs258.*; public class TextReader { public static final int NAME_SIZE=30; public static void main(String args[]) { String name; int age; double salary; if (!new File("seqtext.dat").exists() || !new File("seqtext2.dat").exists())
  • 4. { System.out.println("Files don't exist"); System.exit(1); } TextRead file1 = new TextRead("seqtext.dat"); TextRead file2 = new TextRead("seqtext2.dat"); NumberFormat money = NumberFormat.getCurrencyInstance(); DecimalFormat fmt = new DecimalFormat("##0.##"); String spaces = " "; System.out.println("Text file readern"); do { if (!file1.endOfFile()) { name = file1.readString(); age = file1.readInt(); salary = file1.readDouble(); System.out.print(name); if (name.length() < NAME_SIZE) System.out.print ( spaces.substring(0, NAME_SIZE-name.length()) ); System.out.println ( " " + fmt.format(age) + " " + money.format(salary) ); } if (!file2.endOfFile()) { name = file2.readString(); age = file2.readInt(); salary = file2.readDouble(); System.out.print(name); if (name.length() < NAME_SIZE) System.out.print ( spaces.substring(0, NAME_SIZE-name.length()) ); System.out.println ( " " + fmt.format(age) + " " +
  • 5. money.format(salary) ); } } while (!file1.endOfFile()||!file2.endOfFile()); file1.close(); file2.close(); System.out.println("nTextReader complete; data printed"); } } // This program writes different types of files. // Random, Binary, and Text. // Created 3/29/2004 for the lab 2 cs258 project. import java.io.*; import java.security.*; public class Writers { private final static int RECORDSIZE = 128; private final static int NAME_SIZE = 30; private final static String spaces = " "; // Keyboard input stream. private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[]) { // File related variables variables. Writer out = null; String fileType = null, fileName = null; // Data variables. String name; int age, recordNumber = 0; double salary; String doMore;
  • 6. boolean quit, moreFiles; System.out.println("File writer program"); do { try { do { System.out.print("Enter file type (text, binary, random): "); fileType = in.readLine().toLowerCase(); } while ( !("text".startsWith(fileType) || "binary".startsWith(fileType) || "random".startsWith(fileType)) ); System.out.print("Enter the file name: "); fileName = in.readLine().toLowerCase(); switch (fileType.charAt(0)) { case 't': out = new Text(fileName); break; case 'b': out = new Binary(fileName); break; case 'r': recordNumber = 0; out = new Random( fileName, RECORDSIZE); break; default: throw new InvalidParameterException(); } do { System.out.print("Enter Name: "); name = in.readLine() + spaces; name = name.substring(0,NAME_SIZE); age = getAge(); salary = getSalary();
  • 7. out.write(name, age, salary, recordNumber); recordNumber++; System.out.println("n Type 'quit' to exit: "); doMore = in.readLine().toLowerCase(); quit = (doMore.length()>0 && "quit".startsWith(doMore)); } while (!quit); } catch (InvalidParameterException e) { System.out.println("Unknown case"); System.exit(1); } catch (IOException e) { System.out.println("I/O Error"); } catch (Exception e) { System.out.println("Illegal Entry"); } finally { try { out.close(); } catch(Exception e) {} } System.out.println("Another file? (y/n) "); try { doMore = in.readLine().toLowerCase(); moreFiles = (doMore.length()>0 && "yes".startsWith(doMore)); } catch (Exception e) {moreFiles = false;} } while (moreFiles); System.out.println("File write complete; data is in "+fileName+"n"); } // End void main() // Method to input an age.
  • 8. private static int getAge() { int age = -1; String inputString = null; do { try { System.out.print("Enter Age: "); inputString = in.readLine(); age = Integer.parseInt(inputString); if (age<0 || age>100) throw new Exception(); return age; } catch (Exception e) {System.out.println("Illegal age, try again");} } while (true); } // Method to input a salary. private static double getSalary() { double salary = -1; String inputString = null; do { try { System.out.print("Enter Salary: "); inputString = in.readLine(); salary = Double.parseDouble(inputString); if (salary<0 || salary>1000000) throw new Exception(); return salary; } catch (Exception e) {System.out.println("Illegal salary, try again");} } while (true); } }
  • 9. abstract class Writer { public abstract void write(String name, int age, double salary, int record) throws IOException; public abstract void close(); } class Random extends Writer { RandomAccessFile out; int recordSize; public Random(String fileName, int recordSize) throws FileNotFoundException { } public void write(String name, int age, double salary, int record) throws IOException { } public void close() { } } class Binary extends Writer { DataOutputStream out = null; public Binary(String fileName) throws IOException { } public void write(String name, int age, double salary, int record) throws IOException { } public void close()
  • 10. { } } class Text extends Writer { PrintWriter out = null; public Text(String fileName) throws IOException { } public void write(String name, int age, double salary, int record) throws IOException { } public void close() { } } //*************************************************** ***************** // Keyboard.java // // Facilitates keyboard input by abstracting details about input // parsing, conversions, and exception handling. //*************************************************** ***************** import java.io.*; import java.util.*; public class Keyboard { //************* Error Handling Section **************************
  • 11. private static boolean printErrors = true; private static int errorCount = 0; //----------------------------------------------------------------- // Returns the current error count. //----------------------------------------------------------------- public static int getErrorCount() {return errorCount;} //----------------------------------------------------------------- // Resets the current error count to zero. //----------------------------------------------------------------- public static void resetErrorCount (int count) {errorCount = 0;} //----------------------------------------------------------------- // Returns a boolean indicating whether input errors are // currently printed to standard output. //----------------------------------------------------------------- public static boolean getPrintErrors() {return printErrors;} //----------------------------------------------------------------- // Sets a boolean indicating whether input errors are to be // printed to standard output. //----------------------------------------------------------------- public static void setPrintErrors (boolean flag) {printErrors = flag;} //----------------------------------------------------------------- // Increments the error count and prints the error message if // appropriate. //-----------------------------------------------------------------
  • 12. private static void error (String str) { errorCount++; if (printErrors) System.out.println (str); } //************* Tokenized Input Stream Section ****************** private static String current_token = null; private static StringTokenizer reader; private static BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); //----------------------------------------------------------------- // Gets the next input token assuming it may be on subsequent // input lines. //----------------------------------------------------------------- private static String getNextToken() {return getNextToken (true);} //----------------------------------------------------------------- // Gets the next input token, which may already have been read. //----------------------------------------------------------------- private static String getNextToken (boolean skip) { String token; if (current_token == null) token = getNextInputToken (skip); else { token = current_token; current_token = null;
  • 13. } return token; } //----------------------------------------------------------------- // Gets the next token from the input, which may come from the // current input line or a subsequent one. The parameter // determines if subsequent lines are used. //----------------------------------------------------------------- private static String getNextInputToken (boolean skip) { final String delimiters = " tnrf"; String token = null; try { if (reader == null) reader = new StringTokenizer(in.readLine(), delimiters, true); while (token == null || ((delimiters.indexOf (token) >= 0) && skip)) { while (!reader.hasMoreTokens()) reader = new StringTokenizer(in.readLine(), delimiters,true); token = reader.nextToken(); } } catch (Exception exception) {token = null;} return token; } //----------------------------------------------------------------- // Returns true if there are no more tokens to read on the // current input line. //-----------------------------------------------------------------
  • 14. public static boolean endOfLine() {return !reader.hasMoreTokens();} //************* Reading Section ********************************* //----------------------------------------------------------------- // Returns a string read from standard input. //----------------------------------------------------------------- public static String readString() { String str; try { str = getNextToken(false); while (! endOfLine()) { str = str + getNextToken(false); } } catch (Exception exception) { error ("Error reading String data, null value returned."); str = null; } return str; } //----------------------------------------------------------------- // Returns a space-delimited substring (a word) read from // standard input. //----------------------------------------------------------------- public static String readWord() { String token; try { token = getNextToken(); } catch (Exception exception) { error ("Error reading String data, null value returned.");
  • 15. token = null; } return token; } //----------------------------------------------------------------- // Returns a boolean read from standard input. //----------------------------------------------------------------- public static boolean readBoolean() { String token = getNextToken(); boolean bool; try { if (token.toLowerCase().equals("true")) bool = true; else if (token.toLowerCase().equals("false")) bool = false; else { error ("Error reading boolean data, false value returned."); bool = false; } } catch (Exception exception) { error ("Error reading boolean data, false value returned."); bool = false; } return bool; } //----------------------------------------------------------------- // Returns a character read from standard input. //----------------------------------------------------------------- public static char readChar() { String token = getNextToken(false); char value;
  • 16. try { if (token.length() > 1) { current_token = token.substring (1, token.length()); } else current_token = null; value = token.charAt (0); } catch (Exception exception) { error ("Error reading char data, MIN_VALUE value returned."); value = Character.MIN_VALUE; } return value; } //----------------------------------------------------------------- // Returns an integer read from standard input. //----------------------------------------------------------------- public static int readInt() { String token = getNextToken(); int value; try { value = Integer.parseInt (token); } catch (Exception exception) { error ("Error reading int data, MIN_VALUE value returned."); value = Integer.MIN_VALUE; } return value; } //----------------------------------------------------------------- // Returns a long integer read from standard input. //-----------------------------------------------------------------
  • 17. public static long readLong() { String token = getNextToken(); long value; try { value = Long.parseLong (token); } catch (Exception exception) { error ("Error reading long data, MIN_VALUE value returned."); value = Long.MIN_VALUE; } return value; } //----------------------------------------------------------------- // Returns a float read from standard input. //----------------------------------------------------------------- public static float readFloat() { String token = getNextToken(); float value; try { value = (new Float(token)).floatValue(); } catch (Exception exception) { error ("Error reading float data, NaN value returned."); value = Float.NaN; } return value; } //----------------------------------------------------------------- // Returns a double read from standard input. //----------------------------------------------------------------- public static double readDouble()
  • 18. { String token = getNextToken(); double value; try { value = (new Double(token)).doubleValue(); } catch (Exception exception) { error ("Error reading double data, NaN value returned."); value = Double.NaN; } return value; } }