SlideShare a Scribd company logo
1 of 18
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

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 .pdfatulkapoor33
 
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 ConceptsANUSUYA 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;.docxwilcockiris
 
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 EnhancementsGagan Agrawal
 
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.pptxcherryreddygannu
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentalssirmanohar
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
Evidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docxEvidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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, .docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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.docxtheodorelove43763
 
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 .docxtheodorelove43763
 
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.,.docxtheodorelove43763
 
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.docxtheodorelove43763
 

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

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

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; } }