Question
Using a Java class you wrote, construct a class that implements a collection of objects. Write the Java definition of a collection class that has
Using a Java class you wrote, construct a class that implements a collection of objects. Write the Java definition of a collection class that has a member of an array or ArrayList of instances of the class that you defined.
Enable the user to manage this collection, stored in a disk file, by reading from a file and writing to the file. Write a driver method to instantiate and test your collection class.
/* JAVA CODE I WROTE*/
public class CD { int capacity; String type; int playTime;
public CD() { this.capacity = 0; this.type = ""; this.playTime = 0; }
public CD(int cap, String tp, int plt) { this.capacity = cap; this.type = tp; this.playTime = plt; }
public int getCapacity() { return this.capacity; } public String getType() { return this.type; } public int getPlayTime() { return this.playTime; } public void setCapacity(int cap) { this.capacity = cap; } public void setType(String tp) { this.type = tp; } public void setPlayTime(int plt) { this.playTime = plt; } public String toString() { return " Capacity: " + this.capacity + " Type: " + this.type + " PlayingTime: " + this.playTime; }
public void fileWrite(String fileName) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(this.capacity + "\t" + this.type + "\t" + this.playTime); writer.close(); System.out.println(" File created and written successfully "); } catch (IOException e) { } }
public void fileRead(String fileName) { String line; try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); System.out.println("File reade and displayed on console successfully "); } catch (IOException e) { } }
public static void main(String[] args) { CD cd1 = new CD(900, "RW", 25); CD cd2 = new CD(500, "R", 15);
cd1.setCapacity(1000);
System.out.println("CD details of CD1: "); System.out.println(cd1);
System.out.println("CD details of CD2: "); System.out.println("Capacity: " + cd2.getCapacity()); System.out.println("Type: " + cd2.getType()); System.out.println("Playing Time: " + cd2.getPlayTime());
cd1.fileWrite("CDdetails.txt"); System.out.println("File Details: "); cd1.fileRead("CDdetails.txt"); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started