Question: Write a program that reads from a file created by the program in the previous programming project and displays the following information on the screen:

Write a program that reads from a file created by the program in the previous programming project and displays the following information on the screen: the data for the species having the smallest population and the data for the species having the largest population. Do not assume that the objects in the file are in any particular order. The user gives the file name.
The previous program:
class Species
{
private String name;
private int population;
private double growthRate;
public Species ()
{
name = null;
population =0;
growthRate =0;
}
public Species (String name, int population,
double growthRate)
{
this.name = name;
this.population = population;
this.growthRate = growthRate;
}
public String toString ()
{
return ("Name ="+ name +"
"+
"Population ="+ population +"
"+
"Growth rate ="+ growthRate +"%");
}
}
public class species {
public static void main(String[] args){
ObjectOutputStream outputStream = null;
String fileName = "species.records";
try {
outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
} catch (IOException e){
System.out.println("Error opening output file "+ fileName +".");
System.exit(0);
}
Species califCondor = new Species("Calif. Condor", 27,0.02);
Species blackRhino = new Species("Black Rhino", 100,1.0);
try
{
outputStream.writeObject(califCondor);
outputStream.writeObject(blackRhino);
outputStream.close();
} catch (IOException e)
{
System.out.println("Error!"+ fileName +".");
System.exit(0);
}
try {
inputStream = new ObjectInputStream(new FileInputStream("species.records"));
} catch (IOException e){
System.out.println("Sorry!There was an Error opening the requested file "+ fileName +".");
System.exit(0);
}
Species readOne = null, readTwo = null;
try {
readOne =(Species) inputStream.readObject();
readTwo =(Species) inputStream.readObject();
inputStream.close();
} catch (Exception e){
System.out.println("Error reading from file "+ fileName +".");
System.exit(0);
}
System.out.println("The following was read
"+ "from file "+ fileName +".");
System.out.println(readOne);
System.out.println();
System.out.println(readTwo);
System.out.println("End of program.");
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!