Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please write the code for this in Java, and possibly test it on Netbeans. Multip

ID: 666595 • Letter: P

Question

Please write the code for this in Java, and possibly test it on Netbeans. Multiple people have tried this, but when I use their written code it doesn't compile properly. Also, not to rush, but I need an answer to this somewhat soon.

Write a class named CarPlate encapsulating the concept of a car license plate, assuming that it has the following attributes: the plate number, the state, and its color. Write a client program that creates three CarPlate objects and writes them to a file as objects, then reads them from the file as objects, outputs a description of each of the objects using the toString method (which the CarPlate class should override), and outputs the number of objects. When reading the objects, you should assume that you do not know the number of objects in the file and detect the end of file when an EOFException is thrown by the readObject method.

Explanation / Answer

working java code

import java.io.*;

public class CarPlate implements Serializable {

private String plateNumber;
private String state;
private String color;

public CarPlate() {} // default constructor

public CarPlate(String pNumber, String st, String clr) {
plateNumber = pNumber;
state = st;
color = clr;
} // end overloaded constructor

public String toString() {
String s = "plate number: "+plateNumber;
s += " state: "+state;
s += " color: "+color;
return s;
} // end toString()
} // end class CarPlate

//test class

import java.io.*;

public class TestCarPlate {

public static void main(String[] args) throws IOException {

CarPlate plate0 = new CarPlate("ABC 123", "New Jersey", "Silver");
CarPlate plate1 = new CarPlate("DEF 1000", "Ohio", "Red");
CarPlate plate2 = new CarPlate("GH 3", "Kentucky", "Blue");

File f = new File("cardata.tmp");
ObjectOutputStream oos = null;

try {
FileOutputStream fos = new FileOutputStream(f);
oos = new ObjectOutputStream(fos);
oos.writeObject(plate0);
oos.writeObject(plate1);
oos.writeObject(plate2);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) oos.close();
} // end try

int c = 0;
CarPlate cp;

ObjectInputStream ois = null;

try {
FileInputStream fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
while (true) {
cp = (CarPlate) ois.readObject();
System.out.println(cp.toString());
c++;
} // end while
} catch (EOFException e) {
System.out.println("Number of objects = "+c);
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
} finally {
if (ois != null) ois.close();
} // end try
} // end main()
} // end class TestCarPlate